To say "Hello world" in Python CGI Web Programming in 5 minutes

by Forrest Sheng Bao

I have lotta Python programs for bioinformatics research. I wanted to put them onto the web. I only developed Web apps in PHP before. And it seemed to be a big pain for porting a Python program to the web. But, I figured out in 5 minutes.

First, you need an Apache server on your Linux/Mac OS/Windows box. If you are gonna use data base, you need a database server. There are tons of blogs addressing these issues. So I won't be gossipy here. Suppose everything we mention below happens on your server-even web browsing.

Second, configure cgi in Apache. There are many ways to run a Python program on a web/http interface. I think CGI is the easiest. Assume you are on your own server and using all default settings. On Ubuntu Linux 9.04, the default configuration file for your default website is /etc/apache2/sites-available/default Open it, find the part for cgi directory, and make it like this

ScriptAlias /cgi-bin/ /var/www/cgi-bin/
<Directory "/var/www/cgi-bin">

AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
#Order allow,deny
Require all granted
Allow from all
AddHandler cgi-script .py              # tell Apache to handle every file with .py suffix as a cgi program
AddHandler default-handler .html .htm  # tell Apache to handle HTML files in regular way


The line

ScriptAlias /cgi-bin/ /var/www/cgi-bin/

specifies the path of cgi codes and the actual directory of your program. So when you type, the Apache will look into the directory /var/www/cgi-bin/ of your localhost.

Also, make sure that cgimodule of Apache is enabled. You can enable it by

sudo a2enmod cgi

Now restart your apache. On Ubuntu Linux, by default installation and configuration, it is
sudo /etc/init.d/apache2 restart

Third, write up a Hello, World! program.

#!/usr/bin/env python
print "Content-Type: text/html"
print """\
<head><title>First Python HTTP Programming </title></head>

<h2>Hello World!</h2>

Now open in your web browser and you shall see a hello world in it.



Dilan Leelarathna said...

I am from Sri Lanka. I am going to learn python. This article was very useful for my studies. Thank You!

Anonymous said...

Where do you specify the location of your python installation?

Anonymous said...

Very helpful thanks. You can leave the cgi-bin where it is by default in /usr/lib/cgi-bin/.

Remember to make your scripts 'world executable' e.g chmod 755