Starting CGI Programming in Python

CGI or Common Gateway Interface allow servers, primarily HTTP servers, to interface with external programs like Python, Perl, Ruby scripts or even binary programs written in C/C++. The most popular & most used web server - Apache - can easily be configured for CGI scripts. Let's look at configuring a few popular web servers to run CGI scripts.

Configuring Web Server

Apache

I am using a directory py-bin you may change this to whatever you like, cgi-bin is very popular. Remember to have the executable bit set for your CGI scripts.

Basics

The basic HTTP response can be divided into two parts, the header and the body, so here in the CGI scripts we need to do the same, follow the example code below:

Code: Python

#!/usr/bin/python

## Headersprint"Content-Type: text/html"## telling what type of document we are sendingprint## a blank line to separate the headers from the body

## bodyprint"<h1>Hello World!</h1>"

In Python we would be using the cgi module to ease our tasks like form data, cookies, etc. All CGI scripts have access to the environment variables provided by the web server, below we'll be looking a script which will print all environment variables.