Juanjo Conti Juanjo Conti - 2 months ago 16
Python Question

How to parse BaseHTTPRequestHandler.path

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,

Answer

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.