List comprehension and FieldStorage

Peter Otten __peter__ at web.de
Thu Apr 28 03:05:06 EDT 2005


Derek Basch wrote:

> print [(key, value) for key, value in form.keys() and form[key].value]

and

> bump

The tutorial is always willing to make time for you :-)

>>> import cgi
>>> fs = cgi.FieldStorage(environ=dict(QUERY_STRING="alpha=1&beta=2"))
>>> [(key, fs[key].value) for key in fs.keys()]
[('alpha', '1'), ('beta', '2')]

So you might have come up yourself with the above in the mean time. 
However, it breaks if there are multiple occurrences of the same key:

>>> fs =
cgi.FieldStorage(environ=dict(QUERY_STRING="alpha=1&beta=2&alpha=3"))
>>> [(key, fs[key].value) for key in fs.keys()]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'list' object has no attribute 'value'

A quick glance in the source suggests that

>>> [(mfs.name, mfs.value) for mfs in fs.list]
[('alpha', '1'), ('beta', '2'), ('alpha', '3')]

is a bit more robust. But perhaps you can get hold of the original unparsed
query string and avoid the detour via FieldStorage altogether?

Peter




More information about the Python-list mailing list