2.4. Debugging CGI scripts

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()                                               (1)
print "Content-type: text/plain"                                          (2)
print
print input
	
1

Get data from standard input.

2

Specifying a text/plain content type let you get the raw input string.

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[0] + ") second field: ", query['second']
                                                                          (1)
print "Content-type: text/plain"
print

print "First field is: ", query['first']
	
1

Trace statement: print data on standard error, without disturbing the normal output. Notice that the statement refers to the name of the script, which can help if there are several CGI scripts trace statements intertwined in the server log file.

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                                                   (1)

print "Content-type: text/plain"
print
# the following statement will produce an error
print input
	
1

Errors normaly displayed in the log file will be displayed in the client browser, because this statement changes the sys.stderr value to be the same as sys.stdout.

Exercise 2.11. File upload

Write a CGI that displays the http request for a file upload.

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.py
	
but 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