6. July 2014

Simple HTTP server in Python 3.x on specific port

One very cool feature of Python 3.x is instant web server. Type the following command on command line:

python -m http.server

The Python will start a simple web server serving content from the working directory at URL: http://localhost:8000.

It’s also possible to specify the port to open, simply add the port number as the next parameter:

python -m http.server 8080

The web server by default operates on all network interfaces. It’s possible to restrict which interface to bind by the following command:

python -m http.server -b 192.168.1.10 8080

This web server will be accessible only from http://192.168.1.10:8080

A similar command is also available for old Python 2.x:

python -m SimpleHTTPServer

7. January 2011

How to dump POST request with Python

Python contains one helpful module: SimpleHTTPServer. You can expose local directory via HTTP by the following command:

python -m SimpleHTTPServer

Python will start HTTP server at http://localhost:8000

It is very worthy when you’re doing some tests of web application.

The only problem is that SimpleHTTPServer does not support POST. Sometimes it’s very useful to see the content of POST request.

Is there any simple way how to achieve this in Python?

Here is a small extension of SimpleHTTPServer with do_POST handler:

import SimpleHTTPServer
import SocketServer
import logging
import cgi

PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def do_GET(self):
        logging.error(self.headers)
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

    def do_POST(self):
        logging.error(self.headers)
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })
        for item in form.list:
            logging.error(item)
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

Handler = ServerHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

You can download SimpleServer.py here and start it with command:

python SimpleServer.py