简体   繁体   中英

Calling cgi.FieldStorage for an arbitrary url

I'd like to get field values corresponding to an arbitrary URL. Ie 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!

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})

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM