How to parse BaseHTTPRequestHandler.path

Question:

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,

Asked By: Juanjo Conti

||

Answers:

Answered By: Radomir Dopieralski

Use parse_qs from the urlparse module, but make sure you remove the “/?”:

from urlparse import parse_qs
s = "/?parameter=value&other=some"
print parse_qs(s[2:]) # prints {'other': ['some'], 'parameter': ['value']}

Note that each parameter can have multiple values, so the returned dict maps each parameter name to a list of values.

Answered By: AndiDog

Considering self.path could potentially be hierarchical, you should probably do something like the following :

import urlparse
o = urlparse.urlparse(self.path)
urlparse.parse_qs(o.query)
Answered By: Decoder

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.

Answered By: Maximilian Peters

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'],
        }
Answered By: cornelius
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.