6. July 2014

SimpleHTTPServer in Python 3.x

One very cool feature of Python 2.x is instant web server. You can type following command and Python will start simple http server.

python -m SimpleHTTPServer

This command does not work in Python 3.x. The reason is that SimpleHTTPServer was merged to http.server module.

Correct command for Python 3.x is:

python -m http.server

7. January 2011

How to dump POST request with Python

Python contains one helpful module: SimpleHTTPServer. You can expose local directory via HTTP by 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 content of POST request. E.g. you have an app written in Flex and you want to see content of POST request without starting Flash Builder.

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

Here is 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
  • Where is the fish?

  • Further info

  • Twitter

    Follow @jurajmichalek on twitter.

  • Comments

  • Tags

  • Topics