Evgeny
Evgeny

Reputation: 3274

Calling cgi.FieldStorage for an arbitrary url

I'd like to get field values corresponding to an arbitrary URL. I.e. given "http://example.com/hello?q=1&b=1" I want a dictionary {'q':1, 'b':1}. How do I use cgi.FieldStorage for that?

Thanks!

Upvotes: 0

Views: 651

Answers (2)

John La Rooy
John La Rooy

Reputation: 304355

You can use urlparse to do that

from urlparse import urlparse, parse_qs
qs = urlparse("http://example.com/hello?q=1&b=1").query
parse_qs(qs)

if you must use FieldStorage

cgi.FieldStorage(environ={'REQUEST_METHOD':'GET', 'QUERY_STRING':qs})

Upvotes: 3

Alex Martelli
Alex Martelli

Reputation: 882153

You don't -- you use cgi.parse_qs in 2.5 or earlier, urlparse.parse_qs in 2.6 or later. E.g.:

>>> import urlparse
>>> pr = urlparse.urlparse("http://example.com/hello?q=1&b=1")
>>> urlparse.parse_qs(pr.query)
{'q': ['1'], 'b': ['1']}

Note that the values are always going to be lists of strings -- you appear to want them to be ("scalar") integers, but that really makes no sense (how would you expect ?q=bah to be parsed?!) -- if you "know" there's only one instance of each parameters and those instances' values are always strings of digits, then it's easy enough to transform what the parsing return into the form you want, of course (better, this "known" property can be checked, raising an exception if it doesn't actually hold;-).

Upvotes: 2

Related Questions