Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse http GET and POST parameters from BaseHTTPHandler?

BaseHTTPHandler from the BaseHTTPServer module doesn't seem to provide any convenient way to access http request parameters. What is the best way to parse the GET parameters from the path, and the POST parameters from the request body?

Right now, I'm using this for GET:

def do_GET(self):
    parsed_path = urlparse.urlparse(self.path)
    try:
        params = dict([p.split('=') for p in parsed_path[4].split('&')])
    except:
        params = {}

This works for most cases, but I'd like something more robust that handles encodings and cases like empty parameters properly. Ideally, I'd like something small and standalone, rather than a full web framework.

like image 215
ataylor Avatar asked Mar 22 '10 05:03

ataylor


2 Answers

You may want to use urllib.parse:

>>> from urllib.parse import urlparse, parse_qs
>>> url = 'http://example.com/?foo=bar&one=1'
>>> parse_qs(urlparse(url).query)
{'foo': ['bar'], 'one': ['1']}

For Python 2, the module is named urlparse instead of url.parse.

like image 133
zag Avatar answered Nov 16 '22 16:11

zag


Better solution to an old question:

def do_POST(self):
    length = int(self.headers.getheader('content-length'))
    field_data = self.rfile.read(length)
    fields = urlparse.parse_qs(field_data)

This will pull urlencoded POST data from the document content and parse it a dict with proper urldecoding

like image 16
Mike Avatar answered Nov 16 '22 16:11

Mike