The following describes in detail how to use Python to quickly build an HTTP server and implement a micro-Python HTTP service program. What is the implementation method of the Python HTTP service, so please read this article carefully.
If you urgently need a simple Web Server, but you do not want to download and install complex HTTP service programs, such as Apache and ISS. Then, Python may help you. Python can be used to complete a simple built-in HTTP server. Therefore, you can display your directories and files in HTTP mode. Compile only needs to do one thing, that is, install a Python.
In fact, this is a very useful way to share files. It is very easy to implement a micro HTTP service program. In Python, you only need a command line. Below is the command line: Suppose we need to share our directory/home/haoel and the IP address is 192.168.1.1 ).
This works, and our HTTP service listens on port 8000. You will get the following information:
- $ cd /home/haoel $ python -m SimpleHTTPServer
You can open your Browser IE or Firefox) and enter the following URL:
- http://192.168.1.1:8000
If there is a file named index.html in your directory, the file will become a development page. If there is no such file, the directory list will be displayed. 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()
This completes our Python HTTP service. Note: all these things can work in Windows or Cygwin.
- How to embed Python into C ++ applications?
- In-depth discussion of Ruby and Python syntax comparison
- Introduction to Python
- Python Learning Experience: version, IDE selection and encoding solution
- Analysis of Python GIL and thread security