ataylor ataylor - 5 months ago 22
Python Question

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.

Answer

You could try the Werkzeug modules, the base Werkzeug library isn't too large and if needed you can simply extract this bit of code and you're done.

The url_decode method returns a MultiDict and has encoding support :)

As opposed to the urlparse.parse_qs method the Werkzeug version takes care of:

  • encoding
  • multiple values
  • sort order

If you have no need for these (or in the case of encoding, use Python 3) than feel free to use the built-in solutions.

Comments