Although Example 15-10 doesn’t introduce much that is new about CGI itself, it does
highlight a few new coding tricks worth noting, especially regarding CGI script de-
bugging and security. Let’s take a quick look.
Converting strings in CGI scripts
Just for fun, the script echoes back the name of the server platform by fetching
sys.platform along with the square of the age input field. Notice that the age input’s
value must be converted to an integer with the built-in int function; in the CGI world,
all inputs arrive as strings. We could also convert to an integer with the built-in eval
function. Conversion (and other) errors are trapped gracefully in a try statement to
yield an error line, instead of letting our script die.
But you should never use eval to convert strings that were sent over the
Internet, like the age field in this example, unless you can be absolutely
sure that the string does not contain even potentially malicious code.
For instance, if this example were available on the general Internet, it’s
not impossible that someone could type a value into the age field (or
append an age parameter to the URL) with a value that invokes a system
shell command. Given the appropriate context and process permissions,
when passed to eval, such a string might delete all the files in your server
script directory, or worse!
Unless you run CGI scripts in processes with limited permissions and
machine access, strings read off the Web can be dangerous to run as
code in CGI scripting. You should never pass them to dynamic coding
tools like eval and exec, or to tools that run arbitrary shell commands
such as os.popen and os.system, unless you can be sure that they are
safe. Always use simpler tools for numeric conversion like int and
float, which recognize only numbers, not arbitrary Python code.
Debugging CGI scripts
Errors happen, even in the brave new world of the Internet. Generally speaking, de-
bugging CGI scripts can be much more difficult than debugging programs that run on
your local machine. Not only do errors occur on a remote machine, but scripts generally
won’t run without the context implied by the CGI model. The script in Exam-
ple 15-10 demonstrates the following two common debugging tricks:
Error message trapping
This script assigns sys.stderr to sys.stdout so that Python error messages wind
up being displayed in the response page in the browser. Normally, Python error
messages are written to stderr, which generally causes them to show up in the web
server’s console window or logfile. To route them to the browser, we must make
stderr reference the same file object as stdout (which is connected to the browser
in CGI scripts). If we don’t do this assignment, Python errors, including program
errors in our script, never show up in the browser.
Climbing the CGI Learning Curve| 1161