Python CGI Programming
CGI in long, Common Gateway Interface, is a set of standards, defines how information is exchanged between the web server and a custom script.
Before start with CGI programming with python, first make sure that your web server supports CGI and it is configured to the handle CGI programs. All the CGI programs that is to be executed by the HTTP server are kept in a pre-configured directory. And this directory is called as CGI directory and by convention, it is named as /var/www/cgi-bin. CGI files have .cgi extension, but you can use .py extension as well.
By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. But if you want to specify any directory to run your CGI scripts in python, then comment these lines in the httpd.conf file
<Directory "/var/www/cgi-bin"> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> <Directory "/var/www/cgi-bin"> Options All </Directory>
My First CGI Program in Python
Here is a simple link, which is linked to the CGI script named hello.py. The file, hello.py, is kept in /var/www/cgi-bin directory and it has the following content:
#!/usr/bin/python print "Content-type:text/html\r\n\r\n" print '<html>' print '<head>' print '<title>Hello Word - First CGI Program</title>' print '</head>' print '<body>' print '<h2>Hello Word! This is my first CGI program</h2>' print '</body>' print '</html>'
If you click hello.py, then it will produce the following output:
Hello Word! This is my first CGI program
« Previous Tutorial Next Tutorial »