Christopher Mocock wrote:

> Bit of a python newbie so need a little help with a CGI script I'm
> trying to write. I've got it working fine as long as the fields of the
> form are filled in correctly, however I need to be able to accept blank
> entries. Therefore I want to convert any empty entries to an empty string.
> 
> For example, if I call the following CGI script as:
> 
> http://localhost/cgi-bin/test.cgi?myfield=hello
> 
> ...it prints hello in the browser. But if I call it as:
> 
> http://localhost/cgi-bin/test.cgi?myfield=
> 
> I get an exception. I want it to treat myfield as an empty string and
> not throw an exception.
> 
> Any suggestions?

You can catch the exception:

def test():
    try:
        value = form["myfield"].value
    except KeyError:
        value = ""
    print value

or use form.getlist("myfield") and then check the length of the returned
list of values.

With both options you also have to decide what to do when 'myfield' is given
twice:

http://localhost/cgi-bin/test.cgi?myfield=42&myfield=24

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to