cgi python

Paul Boddie paul at boddie.org.uk
Thu Oct 13 17:13:59 CEST 2005


Python_it wrote:
> I going to use the cgi-handler (mod_python):
>
> http://www.modpython.org/live/mod_python-3.2.2b/doc-html/hand-cgi.html
>
> If I test a simply py script it works

You don't say how you test it, but I imagine that you just point your
browser to the location where the program is published, without
specifying any query parameters - see below for the significance of
this.

[...]

> But if I test a py script with cgi comments (import cgi):
>
> Part of the code
> ============
> import cgi
>
> #get HTTP query parameters
> query = cgi.FieldStorage()
>
> #Get the selected year and month
> selectedYear = int(query["year"].value)

[...]

> KeyError: 'year'

The problem is that if you point your browser to this new program and
don't specify query parameters (eg. ?year=2005&x=10&value=5000 on the
end of the URL) then attempting to get the "year" parameter from the
query object will fail because the parameter doesn't exist - you didn't
specify it.

What you should do is to test for its presence first, just like you
would with a normal Python dictionary, and I believe that the query
object supports the has_key method:

if query.has_key("year"):
    selectedYear = int(query["year"].value)

A more comprehensive alternative, given that the "year" parameter may
not be a number, is to catch any exceptions raised when you try and get
the parameter's value:

try:
    selectedYear = int(query["year"].value)
except KeyError:
    Do something here about the missing parameter.
except ValueError:
    Do something here about a non-integer parameter.

Testing Web applications can be hard, but the traceback tells you
everything you need to know here.

Paul




More information about the Python-list mailing list