Exercise 2.8. Getting raw input
Write a script called debug_cgi.py that prints the input as received by the script:
#! /local/bin/python import sys input=sys.stdin.readlines() print "Content-type: text/plain" print print input
Call this script from a form (debug_cgi.html). This form should have at least two input fields (one entry, called first, and one checkbox, called second).
Does this script use the cgi module? Would it be possible to get the standard input while using this module?
What do you conclude about the way for a Web server to provide input to a CGI script (in case of a POST)?
Exercise 2.9. Tracing
You can put print statements that will display trace information in the server log file (for instance /var/log/apache/error.log), by writing on the sys.stderr file handle:
#! /local/bin/python import sys query = cgi.parse() print >>sys.stderr, "(debug from " + sys.argv + ") second field: ", query['second'] print "Content-type: text/plain" print print "First field is: ", query['first']
Exercise 2.10. Redirecting standard error to the browser
Another very useful feature is to be able to access Python error messages directly on the CGI output, instead of the server log file. The way to achieve this is to redirect sys.stderr to sys.stdout:
#! /local/bin/python import sys sys.stderr = sys.stdout print "Content-type: text/plain" print # the following statement will produce an error print input
Exercise 2.12. Debugging your script directly
An easy way to debug your script can be to run it directly from the Unix prompt:
% ./test.pybut in this case, you need to simulate input from the Web server (and you will have many environment variables unset). One way to achieve this can be:
% QUERY_STRING='first=val1&second=val2' ./test.py