Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
print('')
result = 1 / 0
print('This is a test of a bad Python program')

The script2206.cgi code still has the same division error as the script2205.cgi program,
but now you have added the cgitb.enable() method to enable the debugging feature in the
Python script. The cgitb debugging feature displays full error messages and code when a Python
error occurs in the program.


Now when you run this program from your web browser, you should see a webpage similar to the one
shown in Figure 22.5.


FIGURE 22.5 The debugging output from the script2206.cgi program.

The error message not only tells you what went wrong but also displays the Python code and what
line has the error. Now you can get a better idea of what’s going wrong with your Python code, so you
can get things working more quickly.


While the cgitb.enable() method can be very helpful when you’re debugging a Python web
application, it can also help out any attackers trying to gain insight into your Python code. Another
option you have is to redirect error messages to a log file instead of display them on the webpage. To
do that, you need to add a couple parameters to the enable() method, as shown here:


Click here to view code image


cgitb.enable(display=0, logdir='path')

The display parameter determines whether the error message appears on the webpage. (You can
set the value to 1 if you want the error to appear both on the webpage and in the log file.) The
logdir parameter specifies the folder path where you want the log file to be created. It’s important
to remember that the Apache web server’s Linux account (www-data on the Raspberry Pi) must
have write permissions to that folder. You can use the /tmp folder, as shown here, if you don’t mind

Free download pdf