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
Rating: 4.5/5. From 2 votes.
Please wait...

Leave a comment

7. January 2011 at 11:13 - Rich Internet Application (Tags: , , , , , ). Both comments and pings are currently closed.

2 Responses to “How to dump POST request with Python”

  • Tim Howlett says:

    Many thanks for the above example.

    How do you access the data that has been posted?
    I’ve tried the above and it seems to work but I can’t work out how to get at the information that has been posted. Do fp, headers and environ have to match the data format?

    No votes yet.
    Please wait...
  • georgik says:

    @Tim: Checkout CGI module for Python – http://docs.python.org/2/library/cgi.html

    Example in this article is using cgi.FieldStorage to parser request and create form with fields.

    Try to access self.headers.

    The easiest way how to see available data and objects is to open that script in Debug Mode in IntelliJ Idea with Python plugin or in Eclipse with PyDev.

    No votes yet.
    Please wait...