Scripts should call cgi.FieldStorage only once and before accessing any field values.
When it is called, we get back an object that looks like a dictionary—user input fields
from the form (or URL) show up as values of keys in this object. For example, in the
script, form['user'] is an object whose value attribute is a string containing the text
typed into the form’s text field. If you flip back to the form page’s HTML, you’ll notice
that the input field’s name option was user—the name in the form’s HTML has become
a key we use to fetch the input’s value from a dictionary. The object returned by
FieldStorage supports other dictionary operations, too—for instance, the in expres-
sion may be used to check whether a field is present in the input data.
Before exiting, this script prints HTML to produce a result page that echoes back what
the user typed into the form. Two string-formatting expressions (%) are used to insert
the input text into a reply string, and the reply string into the triple-quoted HTML
string block. The body of the script’s output looks like this:
<TITLE>tutor3.py</TITLE>
<H1>Greetings</H1>
<HR>
<P>Hello, King Arthur.</P>
<HR>
In a browser, the output is rendered into a page like the one in Figure 15-7.
Figure 15-7. tutor3.py result for parameters in a form
Passing parameters in URLs
Notice that the URL address of the script that generated this page shows up at the top
of the browser. We didn’t type this URL itself—it came from the action tag of the prior
page’s form HTML. However, nothing is stopping us from typing the script’s URL
explicitly in our browser’s address field to invoke the script, just as we did for our earlier
CGI script and HTML file examples.
Climbing the CGI Learning Curve| 1153