pistacchio pistacchio - 2 months ago 42
HTTP Question

Python: How do I get key/value pairs from the BaseHTTPRequestHandler HTTP POST handler?

given the simplest HTTP server, how do I get post variables in a BaseHTTPRequestHandler?

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
def do_POST(self):
# post variables?!

server = HTTPServer(('', 4444), Handler)

# test with:
# curl -d "param1=value1&param2=value2" http://localhost:4444

I would simply like to able to get the values of param1 and param2. Thanks!

adw adw
Answer Source
def do_POST(self):
    ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
    if ctype == 'multipart/form-data':
        postvars = cgi.parse_multipart(self.rfile, pdict)
    elif ctype == 'application/x-www-form-urlencoded':
        length = int(self.headers.getheader('content-length'))
        postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
        postvars = {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download