Handling empty form fields in CGI

C

Christopher Mocock

Hi all,

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?

Thanks in advance, Chris.

Script below:


#!/usr/bin/env python2
# Import CGI and CGI debug libraries
import cgi
import cgitb; cgitb.enable()

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

# Start of main code
print 'Content-type: text/html'
print

# Get the contents of the query string
form = cgi.FieldStorage()

test()
 
P

Peter Otten

Christopher said:
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
 
P

Paul Boddie

Christopher said:
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.
[...]

form = cgi.FieldStorage()

Try replacing this with...

form = cgi.FieldStorage(keep_blank_values=1)

Paul
 
C

Christopher Mocock

Paul said:
Try replacing this with...

form = cgi.FieldStorage(keep_blank_values=1)

Paul

That worked a treat. Thanks very much to both who replied.

Chris.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top