Begin by writing "import cgi". Do not use "from cgi import*" -- the module defines all sorts of names for its own use or forbackward compatibility that you don't want in your namespace.
When you write a new script, consider adding the line:
import cgitb; cgitb.enable()
This activates a special exception handler that will display detailedreports in the Web browser if any errors occur. If you'd rather notshow the guts of your program to users of your script, you can havethe reports saved to files instead, with a line like this:
import cgitb; cgitb.enable(display=0, logdir="/tmp")
It's very helpful to use this feature during script development.The reports produced bycgitb provide information thatcan save you a lot of time in tracking down bugs. You can alwaysremove thecgitb line later when you have tested your scriptand are confident that it works correctly.
To get at submitted form data,it's best to use theFieldStorage class. The other classesdefined in this module are provided mostly for backward compatibility.Instantiate it exactly once, without arguments. This reads the formcontents from standard input or the environment (depending on thevalue of various environment variables set according to the CGIstandard). Since it may consume standard input, it should beinstantiated only once.
TheFieldStorage instance can be indexed like a Pythondictionary, and also supports the standard dictionary methodshas_key() andkeys(). The built-inlen()is also supported. Form fields containing empty strings are ignoredand do not appear in the dictionary; to keep such values, providea true value for the the optionalkeep_blank_values keywordparameter when creating theFieldStorage instance.
For instance, the following code (which assumes that theContent-Type: header and blank line have already beenprinted) checks that the fieldsname andaddr are bothset to a non-empty string:
form = cgi.FieldStorage()if not (form.has_key("name") and form.has_key("addr")): print "<H1>Error</H1>" print "Please fill in the name and addr fields." returnprint "<p>name:", form["name"].valueprint "<p>addr:", form["addr"].value...further form processing here...Here the fields, accessed through "form[key]", arethemselves instances ofFieldStorage (orMiniFieldStorage, depending on the form encoding).Thevalue attribute of the instance yields the string valueof the field. Thegetvalue() method returns this string valuedirectly; it also accepts an optional second argument as a default toreturn if the requested key is not present.
If the submitted form data contains more than one field with the samename, the object retrieved by "form[key]" is not aFieldStorage orMiniFieldStorageinstance but a list of such instances. Similarly, in this situation,"form.getvalue(key)" would return a list of strings.If you expect this possibility(when your HTML form contains multiple fields with the same name), usetheisinstance() built-in function to determine whether youhave a single instance or a list of instances. For example, thiscode concatenates any number of username fields, separated bycommas:
value = form.getvalue("username", "")if isinstance(value, list): # Multiple username fields specified usernames = ",".join(value)else: # Single or no username field specified usernames = valueIf a field represents an uploaded file, accessing the value via thevalue attribute or thegetvalue() method reads theentire file in memory as a string. This may not be what you want.You can test for an uploaded file by testing either thefilenameattribute or thefile attribute. You can then read the data atleisure from thefile attribute:
fileitem = form["userfile"]if fileitem.file: # It's an uploaded file; count lines linecount = 0 while 1: line = fileitem.file.readline() if not line: break linecount = linecount + 1
The file upload draft standard entertains the possibility of uploadingmultiple files from one field (using a recursivemultipart/* encoding). When this occurs, the item will bea dictionary-likeFieldStorage item. This can be determinedby testing itstype attribute, which should bemultipart/form-data (or perhaps another MIME type matchingmultipart/*). In this case, it can be iterated overrecursively just like the top-level form object.
When a form is submitted in the ``old'' format (as the query string oras a single data part of typeapplication/x-www-form-urlencoded), the items will actuallybe instances of the classMiniFieldStorage. In this case, thelist,file, andfilename attributes arealwaysNone.
| Python Library Reference |