This is meant as a simple writeup to fill a gap in various "HOWTO"'s that I read when trying to setup my Apache2 server to process python scripts as CGI, though it would apply to any cgi scripts (perl scripts, compiled binaries...).
I've been developing for years (C, C++, PHP), but had never delved into python before, and I wanted to be able to have my scripts have a web interface.
The first step is getting Apache2 to recognize that my .py files were to be executed and not spit out as text files.
docs.python.org has some nice HOWTOs (http://docs.python.org/3.3/howto/webservers.html) on how to think about python and the web, and apache.org has mountains of documentation (http://httpd.apache.org/docs/2.2/howto/cgi.html) relating to running CGIs. What I didn't find was a simple guide on how to set it up. I'm a developer, not a sys-admin, and while I like knowing how to configure Apache and tune my linux boxes, sometimes I just want to get my webserver up and running and start coding.
So, in case anyone was going through the same situation as me, here is my quick and dirty setup.
For reference, this setup was done on Ubuntu 13.10, using ubuntu's default apache2 installation, and python3.
I'm also assuming you know how to configure apache for a basic html site. There are lots of HOWTO's for that.
Starting the basics:
apache install: sudo apt-get install apache2
python install: sudo apt-get install python
python3 install: sudo apt-get install python3
The first step, which in my PHP experience I never had to do, is not mentionned in the guides above is to enable CGI processing in apache.
sudo a2enmod cgi
This will automatically enable mod_cgid if your server is configured with a multi-threaded MPM, which was the case for me.
Then you can either make a folder in your site's path where your cgi files will live, or configure certain directories to handle certain file types as cgi scripts.
This is described well in the apache2 doc above, but essentially you to make all files in a cgi folder be executed, you would use this conf:
and to allow .py files to be executed as scripts in a particular folder you would use this conf:
AddHandler cgi-script .py
Once you have that, if you're running python 3, you can make a python script like this one, and stick it in whichever folder is configured for cgi:#!/usr/bin/env python
# -*- coding: UTF-8 -*-# enable debugging
cgitb.enable() print("Content-Type: text/html;charset=utf-8")
print() print("Hello World!")
You can change the first line from
in case the default is python and you want this script to be parsed by python3