data user account. You can use the chown command to change the group owner of
your files to the www-data user account:
Click here to view code image
sudo chown www-data /usr/lib/cgi-bin/script2204.cgi
Then you change the permissions on the file so only the www-data user can access it:
Click here to view code image
sudo chmod 700 /usr/lib/cgi-bin/script2204.cgi
Now no one else on the system can read the file, but it’ll work just fine on the Apache
web server.
Debugging Python Programs
The downside to running your Python programs using CGI is that you don’t get any feedback if you
have any Python scripting errors in your code. If anything goes wrong in the Python script, you won’t
get any output in the client browser. Listing 22.2 shows a Python script with a math error that will
cause problems.
LISTING 22.2 Running a Python Program That Has an Error
Click here to view code image
#!/usr/bin/python3
print('Content-Type: text/html')
print('')
result = 1 / 0
print('This is a test of a bad Python program')
You need to copy this code into the /usr/lib/cgi-bin folder as the file script2205.cgi,
change the permissions on the file, and then try to run it in your web browser. The mathematical
equation in line 5 attempts to divide by 0, which causes an exception in the Python code. However,
when you run this in your web browser, you don’t see any Python error messages. In fact, you don’t
see any output in the browser window!
Fortunately, there’s an easier way to troubleshoot Python code in your webpages. The Python cgitb
module provides simple debugging output for your Python scripts. By referencing the cgitb module,
you can run the enable() method to enable debugging in the output. Listing 22.3 shows the
script2206.cgi program, which adds the enable() method to the bad Python program code.
LISTING 22.3 Displaying Errors from a Python Web Program
Click here to view code image
#!/usr/bin/python3
import cgitb
cgitb.enable()
print('Content-Type: text/html')