[Tutor] environment data [CGI]
Fri, 28 Dec 2001 22:45:02 -0800 (PST)
On Fri, 28 Dec 2001, Sean 'Shaleh' Perry wrote:
> > cgi module leaves me baffled, but if I can just read the bloddy
> > environment variable I can run with it from there.
> import os.environ
> print os.environ['MY_DATA']
> The cgi module for python passes os.environ as a parameter:
> environ = os.environ
> cgi.py is a lot like rfc822, it parses headers and other data storing
> them in a dictionary and giving you access to them as if the returned
> item was a dictionary itself.
The documentation hides a nice example of the cgi module in action here:
form = cgi.FieldStorage()
if not (form.has_key("name") and form.has_key("addr")):
print "Please fill in the name and addr fields."
print "<p>name:", form["name"].value
print "<p>addr:", form["addr"].value
So cgi.FieldStorage() almost behaves like a dictionary, with the exception
that to get at the actual value, we need to do something like
'form[key].value' instead of just 'form[key]'. Why?
There are good reasons for this: forms can have more than strings! Their
values can be uploaded files as well, and the bottom of the link:
talks about this in more detail. That's one big reason why
cgi.FieldStorage() is a little more awkward to use than a dictionary.
Also, there's a lot of resources you can look at for more CGI examples.
Here are two that may interest you:
The devshed.com article is especially good, as it has a lot of examples