[Tutor] CGI File Woes

Martin Walsh mwalsh at groktech.org
Sun Sep 30 19:07:02 CEST 2007


wormwood_3 wrote:
>>> I've never used cgitb (and until now didn't know it existed!)
>>> so can't comment.
> 
> I had not heard of it until this week when I started working on CGI stuff, but I have found it super handy! All you have to do it "import cgitb; cgitb.enable()" and all tracebacks will get printed to nicely formatted HTML output on the page you were trying to load.
> 

No doubt cgitb is a great tool for debugging cgi, but IIUC there are at
least two instances when you will not get the pretty printed tracebacks
in the browser when using cgitb. One is after, what I would call, a
'compile time' exception such as SyntaxError, in your python code. The
other is when the python code runs without exception, but you have not
separated the header and the document content with a newline. At least,
I have found these to be true when using apache-cgi.

Consider the following examples:

#!/usr/bin/env python
# raises a SyntaxError

import cgi
import cgitb; cgitb.enable()

print "Content-type: text/html\n\n"
# NOTE: purposeful misspelling of the print statement
prin "<html><body><p>Hello, world!</p></body></html>"

# the code above will produce a server 500, with apache
# complaining about "premature end of script headers"

...

#!/usr/bin/env python
# good python, bad data

import cgi
import cgitb; cgitb.enable()

print "Content-type: text/html"
print "<html><body><p>Hello, world!</p></body></html>"

# this is syntactically correct python, and will
# run from the command line, but the html header
# and html content have no separation, so apache
# will consider all of it to be header info, resulting
# in another server 500, "malformed header"

As others have advised, under these circumstances you can review the
apache error log (if your webhost allows it). Or roll-your-own logging
equivalent, and run your cgi from a terminal to catch SyntaxErrors and
the like.

HTH,
Marty


More information about the Tutor mailing list