Handling empty form fields in CGI

Christopher Mocock chris at wavestore.com
Fri Jan 26 12:21:40 EST 2007


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()




More information about the Python-list mailing list