CGI Scripts

Patricia Hawkins phawkins at spamnotconnact.com
Sat Mar 4 20:58:55 EST 2000


>>>>> "AME" == Anders M Eriksson <anders.eriksson at morateknikutveckling.se> writes:
AME> First I would add two 'debug' lines to the script

AME> sys.stderr = sys.stdout
AME> print "Content-Type: text/plain\n"

...

AME> One thing I have noticed is that if I get an error/exception in the
AME> script then I get somekind of default blank HTML-page.

Or you could read documentation in cgi.py and follow the debugging
suggestions contained therein:
.................

Fortunately, once you have managed to get your script to execute
*some* code, it is easy to catch exceptions and cause a traceback to
be printed.  The test() function below in this module is an example.
Here are the rules:


        1. Import the traceback module (before entering the
           try-except!)
        
        2. Make sure you finish printing the headers and the blank
           line early
        
        3. Assign sys.stderr to sys.stdout
        
        3. Wrap all remaining code in a try-except statement
        
        4. In the except clause, call traceback.print_exc()

For example:

        import sys
        import traceback
        print "Content-type: text/html"
        print
        sys.stderr = sys.stdout
        try:
                ...your code here...
        except:
                print "\n\n<PRE>"
                traceback.print_exc()

Notes: The assignment to sys.stderr is needed because the traceback
prints to sys.stderr.  The print "\n\n<PRE>" statement is necessary to
disable the word wrapping in HTML.

If you suspect that there may be a problem in importing the traceback
module, you can use an even more robust approach (which only uses
built-in modules):

        import sys
        sys.stderr = sys.stdout
        print "Content-type: text/plain"
        print
        ...your code here...

This relies on the Python interpreter to print the traceback.  The
content type of the output is set to plain text, which disables all
HTML processing.  If your script works, the raw HTML will be displayed
by your client.  If it raises an exception, most likely after the
first two lines have been printed, a traceback will be displayed.
Because no HTML interpretation is going on, the traceback will
readable.

When all else fails, you may want to insert calls to log() to your
program or even to a copy of the cgi.py file.  Note that this requires
you to set cgi.logfile to the name of a world-writable file before the
first call to log() is made!

-- 
Patricia

Successfully verbose user of speech recognition software.



More information about the Python-list mailing list