How to parse BaseHTTPRequestHandler.path

Viewed 25883

I'm using Python's BaseHTTPRequestHandler. When I implement the do_GET method I find myself parsing by hand self.path

self.path looks something like:

/?parameter=value&other=some

How should I parse it in order to get a dict like

{'parameter': 'value', 'other':'some'}

Thanks,

5 Answers

In case somebody needs it for Python3:

import urllib.parse
s = "/?parameter=value&other=some"
print(urllib.parse.parse_qs(s[2:]))
>>> {'other': ['some'], 'parameter': ['value']}

urlparse was renamed to urllib.parse in Python3.

You can do this easily with cgi.FieldStorage using the instance variables that BaseHTTPRequestHandler provides:

form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={
            'REQUEST_METHOD': 'POST',
            'CONTENT_TYPE': self.headers['Content-Type'],
        }
Related