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
  • Quick search

  • Links

  • Twitter

    Follow @jurajmichalek on twitter.

  • Comments

  • Tags

  • Topics