1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Starting CGI Programming in Python

Discussion in 'Python' started by pradeep, Jul 27, 2012.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    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


    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.

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



    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:

    ## 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.

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


    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:

    # 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 "Welcome %s, from %s" % (user_name,user_city)


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

    ## 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()
    ## body
    print "Cookie set with: <br/><pre>" + cookie.output() + "</pre>"

Share This Page