36

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,

1

5 Answers 5

39

Python 2. 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)
Sign up to request clarification or add additional context in comments.

Comments

32

In case somebody needs it for Python3:

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

urlparse was renamed to urllib.parse in Python3.

1 Comment

You might want to replace import urllib with import urllib.parse for PyCharm to recognise the function correctly, even though this is not required for it to work.
30

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.

1 Comment

in python3: from urllib.parse import parse_qs
2

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

Comments

0

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'],
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.