Page 336 -
P. 336
data delivery
The data is delivered to your CGI script
In addition to running your webapp, the web server also arranges to deliver
any submitted form data to your waiting CGI script. Python’s cgi library
converts the data into a dictionary and, as you already know, provides you
with convenient access to the submitted data:
All of your form’s data
has been added to the
import cgi
“form” dictionary.
form = cgi.FieldStorage()
Additional information about the web request is also available to you via the
web server’s environment. Typically, you won’t need to access or use this data
directly. However, occasionally, it can be useful to report on some of it.
Here is some code that takes advantage of Python’s built-in support for
querying your CGI script’s environment using the os library, assuming the
environment values have been set by a friendly web server. Note that the data
in the enviroment is available to your code as a dictionary.
import os Be sure to include the
import time “os” library in your list of
import sys imports.
Query three environment variables
addr = os.environ['REMOTE_ADDR']
host = os.environ['REMOTE_HOST'] and assign their values to variables.
method = os.environ['REQUEST_METHOD']
cur_time = time.asctime(time.localtime()) Get the current time.
Display the
queried data print(host + ", " + addr + ", " + cur_time + ": " + method, file=sys.stderr)
on standard
error.
Let’s exploit both code snippets on this page to log the data sent from a form
to your web server’s console. When you are convinced that the data is arriving
at your web server intact, you can extend your code to store the received data
in your model.
Let’s write a CGI to display your form’s data.
300 Chapter 9