Start CGI Scripting using Python and Apache Server

The Common Gateway Interface (CGI) is a standard protocol that defines how webserver software can delegate the generation of webpages to a console application.
Such applications are known as CGI scripts – they are usually written in a scripting language.

Python is a free interpreted and object oriented programming that allows you to create any type of applications compatible with all common operating systems.
You can deploy stand-alone applications or CGI scripts. There are many web servers that provide support for deploying Python scripts.

If you are using an Apache web server on Windows platform, you have many alternatives to set up a certain configuration that will allow you to run Python scripts through CGI. The configuration of Apache web server can be performed by editing the httpd.conf file.

First you will need to download and install the latest Python for Windows distribution package. It is recommended to install it directly on the root of the c: drive with the executable file (python.exe) situated in c:\Python directory. The file httpd.conf is located in the apache installation directory in a folder called conf.

This file contains the usual Apache configuration directives that can be enabled by uncommenting a certain line. In case of Python CGI scripts, the line containing the AddHandler directive from the http.conf file must have the next structure:

AddHandler cgi-script .cgi .py .pl

In this way, Apache web server will treat Python and Perl files as CGI scripts. The second modification that must be made to Apache configuration file is the specification of the location of your cgi-bin directory by adding the full path to it in the next line (you must replace C:/apache/cgi-bin with the path of your cgi-bin directory):

ScriptAlias /cgi-bin/ "c:/apache/cgi-bin/"

After you save the http.conf file and restart the Apache web server, you will have support to run Python scripts. You can test if the server configuration was successful with the next example (copy and paste the code in a text file and save it as test.py):

#!C:/Python31/python.exe
 
import cgi
import cgitb
cgitb.enable()  # for troubleshooting
 
#print header
print "Content-type: text/html"
print
print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
print "<html>"
print "<head>"
print "<title>Python CGI Hello World</title>"
print "</head>"
print "<body>"
print "<p>Hello, world!</p>"
print "</body>"
print "</html>"

The file test.py must be copied in your cgi-bin directory. Then type into your web browser address bar:

http://localhost/cgi-bin/test.py

Now we can see browser printing ‘Hello World’..

Reference :  Softpedia , Wikipedia

951 views
CGI, Python

Leave Comment

(required)

(required)