code base 5000
code base 5000

Reputation: 4102

Handling HTTP Query Parameters

I have a simple server that will return JSON to a user. I want the to provide some inputs to the service, so I use query parameters:

/path?paramName=paramValue&paramName2=paramValue2....&paramNamen=paramValuen

In Python, what is the best way of parsing out these parameters?

My server is a threaded server defined as such:

class ThreadingSimpleServer(SocketServer.ThreadingMixIn,
                            BaseHTTPServer.HTTPServer):
    """ simple threaded server """
    pass

In my request handler, I implemented a do_GET().

Should I have this function split based on the ? to separate out the path from the parameters and then split again on the & or is there a better way to do this?

Upvotes: 0

Views: 205

Answers (1)

user1907906
user1907906

Reputation:

Use the functions from urllib.parse:

import urllib.parse

u = "http://java.dzone.com/articles/python-201-decorators?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Fpython+%28Python+Zone%29"
p = urllib.parse.urlparse(u)
q = urllib.parse.parse_qs(p.query)
print(q)

Output:

{'utm_campaign': ['Feed: zones/python (Python Zone)'],
 'utm_medium': ['feed'],
 'utm_source': ['feedburner']}

Upvotes: 1

Related Questions