views:

17

answers:

2

Hi!

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!

+2  A: 

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;-).

Alex Martelli
I'll probably stick with FieldStorage, in case I change my mind and switch to processing POST. But it's good to know an alternative way. Thanks!
Evgeny
+2  A: 

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})
gnibbler
Thanks! That's *exactly* what I need. :-)
Evgeny