How to parse BaseHTTPRequestHandler.path

0 votes
asked Sep 24, 2010 by juanjo-conti

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:


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

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


4 Answers

0 votes
answered Sep 24, 2010 by radomir-dopieralski
0 votes
answered Sep 24, 2010 by andidog

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.

0 votes
answered Sep 12, 2011 by decoder

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

import urlparse
o = urlparse.urlparse(self.path)
0 votes
answered Sep 26, 2016 by maximilian-peters

In case somebody needs it for Python3:

import urllib
s = "/?parameter=value&other=some"
>>> {'other': ['some'], 'parameter': ['value']}

urlparse was renamed to urllib.parse in Python3.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter