Do you know? Using Python, you can quickly build an HTTP server to implement a micro Python HTTP service program! The following describes how to implement the Python HTTP service.
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)
- $ cd /home/haoel
- $ python -m SimpleHTTPServer
This works, and our HTTP service listens on port 8000. You will get the following information:
- Serving HTTP on 0.0.0.0 port 8000 ...
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.
- Analysis of Python 3.1 core language changes
- PHP veteran talks about the basic features of PHP and Python
- Comparison of Ruby and Python syntax
- Ruby usage tips: find efficient implementations
- Dialogue with the father of Python: the path to success in Python