Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Starting CGI Programming in Python (http://www.go4expert.com/articles/starting-cgi-programming-python-t28793/)

pradeep 27Jul2012 14:58

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.

Code:

ScriptAlias /py-bin/

<Directory "/var/www/py-bin">
   AllowOverride None
   Options ExecCGI
   Order allow,deny
   Allow from all
</Directory>


nGinx

Wiki

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

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

## body
print "<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.

Code: Python

#!/usr/bin/python

import os

print "Content-type: text/html"
print
print "<h3>Environment Variables</h3>"
for param in os.environ.keys():
  print "<b>%s</b>: %s</br>" % (param,os.environ[param])


Forms



Form data passed by GET/POST methods can be accessed using the Python cgi module, the demo script that follows should be enough to get an idea of it's usage:

Code: Python

#!/usr/bin/python

# import cgi module
import cgi

# get form data using the FieldStorage method, which returns an object
form = cgi.FieldStorage()

# Get data from fields
user_name = form.getvalue('name')
user_city  = form.getvalue('city')

print "Content-Type: text/html"
print

print "Welcome %s, from %s" % (user_name,user_city)


Cookies



Reading & setting cookies in Python CGI scripts is made easier with the Python Cookie module, let's see how to work with cookies.

Code: Python

#!/usr/bin/python

## load the modules
import Cookie, datetime

## calculate the expiration time, you can set any expiry as you like
expiration = datetime.datetime.now() + datetime.timedelta(days=30)
## Cookie object
cookie = Cookie.SimpleCookie()

## cookie 1
cookie["user_pref"] = 'name=Pradeep&loc=Kol'
cookie["user_pref"]["domain"] = ".pradeep.net.in"
cookie["user_pref"]["path"] = "/"
cookie["user_pref"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")

## cookie 2
cookie["theme"] = 'thm=abc.html&color=red'
cookie["theme"]["domain"] = ".pradeep.net.in"
cookie["theme"]["path"] = "/"
cookie["theme"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")

## output the cookie with the headers
print "Content-type: text/html"
print cookie.output()
print

## body
print "Cookie set with: <br/><pre>" + cookie.output() + "</pre>"



All times are GMT +5.5. The time now is 07:10.