Quantcast
submit to reddit       
       

Writing CGI scripts in Python

In the last post, I looked at CGI scripting in Bash. The principles are pretty much the same when you use Python; you need a line to specify which interpreter should execute the script. There needs to be a header, which at the very least should specify the content-type, and as before, anything printed to stdout after the header is displayed in the browser that made the request. Before we can use Python scripts in Apache, we need to update its settings.

How to enable .py scripts in Apache2

By default Python is configured to only execute scripts with specific endings such as .cgi. In order to make Apache execute .py files, you need to edit a configuration file. In a terminal type this command:

sudo leafpad /etc/apache2/sites-enabled/000-default &

This file contains settings for the default site (you can create other sites on the same server). Look for a section of code that looks like this:

<Directory "/usr/lib/cgi-bin">
...
</Directory>

Add the following line inside the above section of code:

AddHandler cgi-script .py

In a terminal window, type this command to reload Apache's configuration files:

sudo service apache2 reload

Now type this code into a text editor, and save it as /usr/lib/cgi-bin/hello.py:

#!/usr/bin/env python
print "Content-type: text/html\n\n"
print "<h1>Hello World</h1>"

Make the file executable using this command:

$ sudo chmod +x hello.py

As in the previous post, you can execute this script by accessing it through your browser. The IP address of my Raspberry Pi is 192.168.0.4, so I typed this address into my browser: http://192.168.0.4/cgi-bin/hello.py. Once again, you should see the words "Hello World" in large letters.

How do I debug my Python scripts?

There are many different ways of debugging CGI scripts. One of the basic methods is to enable traceback print outs in Python scripts. You can do this by importing modules cgi and cgitb. If you import cgitb, it won't work unless you enable it at the start of your scripts:

#!/usr/bin/env python

import cgi
import cgitb

cgitb.enable()

print "Content-type: text/html\n\n"

print "<h1>Hello World</h1>"

You can also get some information about script problems from /var/log/apache2/error.log. You need to scroll down to the end of this file to see the most recent errors.


Comments

Comments

comments powered by Disqus

Follow me


This site is powered by Pyplate, a lightweight Python CMS for the Raspberry Pi.