Apache Server Configuration To Support Python CGI Scripts

Mar 28, 2008 16:02 GMT  ·  By

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:

code
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):
code
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):
code
#!c:/Python/python.exe -u

print "Content-type: text/html"
print

print "The First Python Script On Server Side"
print "The sum of two numbers evaluation"
print "3+5 = ",3+5
The file test.py must be copied in your cgi-bin directory. Then type into your web browser address bar:
code
http://localhost/cgi-bin/test.py
You will notice that the script will output the HTML code from lines 4 and 5 and also evaluate the sum of two numbers in line 6 and display it. The first line (#!c:/Python24/python.exe -u) shows the path to the script interpreter and the -u option will determine the interpreter to run unbuffered in order to avoid errors. The second line of the script indicates to the web browser the type of data that must be rendered.

This is only a simple script, but its purpose is to allow you to test a custom Apache server configuration. If you want to modify a Python script on an Apache web server on Windows in order to test the influence of various variables, this method of Apache server configuration to enable support for Python CGI scripts could save you a lot of time.