Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse BaseHTTPRequestHandler.path

Tags:

python

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,

like image 487
Juanjo Conti Avatar asked Sep 24 '10 16:09

Juanjo Conti


4 Answers

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)
like image 126
Decoder Avatar answered Nov 04 '22 07:11

Decoder


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.

like image 42
AndiDog Avatar answered Nov 04 '22 07:11

AndiDog


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.

like image 24
Maximilian Peters Avatar answered Nov 04 '22 07:11

Maximilian Peters


The cgi and urlparse modules have that: https://docs.python.org/2/library/urlparse.html#urlparse.parse_qs

like image 2
Radomir Dopieralski Avatar answered Nov 04 '22 06:11

Radomir Dopieralski