Ultra simple Python HTTP service

  • 2021-07-24 11:22:34
  • OfStack

If you need a simple Web Server, but you don't want to download and install the complex HTTP services, such as Apache, ISS, etc. Then, Python may help you. Using Python, you can complete a simple built-in HTTP server. Therefore, you can display your directories and files in HTTP. You only need to do one thing, that is, install an Python.

Actually, this is a very useful way to share files. It is very simple to realize a micro HTTP service program. Under Python, only one command line is needed. Here's 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 will do, 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 you have a file named index. html in your directory, this file will become a default page. If you don't have this file, the directory list will be displayed.

If you want to change the port number, you can use the following command:

$ python -m SimpleHTTPServer 8080

If you only want this HTTP server to serve the local environment, then you need to customize your Python program. Here 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 under Windows or Cygwin.

Summarize


Related articles: