Python built-in HTTP server SimpleHTTPServer User Guide, python built-in Server
First, ensure that Python is installed. I have installed version 2.x. By the way, my operating system is WIN7. In fact, what operating system is not important for Python. Python has a built-in simple HTTP server. You only need to run a line of command under the command line, and an HTTP server will get up:
python -m SimpleHTTPServer 80
Port 80 is optional. If this parameter is left blank, the default port 8000 is used. Note: This will set the current folder as the default Web directory, and try to enter the local address in the browser:
Http: // localhost: 80
If the file contains an index.html file, the file is displayed by default. Otherwise, all files in the directory are displayed in the file list. This has already achieved the most basic purpose of file sharing. You can create a script and create a shortcut to easily start file sharing. If you have more requirements, you can customize them based on your needs. For more information, see the official SimpleHTTPServer documentation or directly view the source code. For more information, see:
import SimpleHTTPServerimport SocketServerPORT = 8000Handler = SimpleHTTPServer.SimpleHTTPRequestHandlerhttpd = SocketServer.TCPServer(("", PORT), Handler)print "serving at port", PORThttpd.serve_forever()
To change the port number, run the following command:
python -m SimpleHTTPServer 8080
If you only want this HTTP server to serve the local environment, you need to customize your Python program. The following is an example:
import sys import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HandlerClass = SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" if sys.argv[1:]: port = int(sys.argv[1]) else: port = 8000 server_address = ('127.0.0.1', port) HandlerClass.protocol_version = Protocol httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever()
Note: all these things can work in Windows or Cygwin.
Articles you may be interested in:
- Use Python to compile a super guide for HTTP servers
- Summary of http request repository in Python
- Summary of how python sends HTTP requests
- Use the httplib module to create an HTTP client in Python
- Python urllib, urllib2, and httplib Capture web page code instances
- Python automatically retries HTTP connection decorator
- Use Python's Treq on Twisted for HTTP stress testing
- Python disguised as HTTP/1.1 when collecting data using scrapy
- Using pycurl in Python to monitor http Response Time scripts