CGI: Assign FieldStorage values to variables

Chris Angelico rosuav at gmail.com
Wed Aug 17 05:41:41 EDT 2011


On Wed, Aug 17, 2011 at 10:19 AM, Gnarlodious <gnarlodious at gmail.com> wrote:
> import cgi, os
> os.environ["QUERY_STRING"] = "name1=Val1&name2=Val2&name3=Val3"
> form=cgi.FieldStorage()
>
> form
>
> dict = {}
> for key in form.keys(): dict[ key ] = form[ key ].value
>

You could probably use a list comp for this, but there's not a lot of
difference. (By the way, you should be aware that you're shadowing the
builtin 'dict' here. That's not a problem, but be aware.)

dict.update(((key,form[key].value) for key in form))

That's a generator that returns a (key,value) tuple for each form
element, which update() will happily use.

But the last line:
> locals().update(dict)
is, IMHO, a very bad idea. Rename your dictionary to 'request' or
'data' or 'form' or something, and then reference form['name3']
instead; or, be explicit:
name3=form['name3']

Incidentally, you seem to be working at the module level, where
locals() is globals() (and I mean that literally - 'locals() is
globals()' is True). You may not be able to do this with locals() in a
function:
http://docs.python.org/library/functions.html#locals

Chris Angelico



More information about the Python-list mailing list