Python
  Home arrow Python arrow Page 4 - Writing CGI Programs in Python
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Writing CGI Programs in Python
By: Preston Landers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 66
    1999-08-25


    Table of Contents:
  • Writing CGI Programs in Python
  • Why should my next CGI project be in Python?
  • Your First CGI program in Python
  • Getting some real work done
  • Defining a useful Display function
  • Putting the pieces together
  • Simple Database Access
  • Other Resources and Links

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Writing CGI Programs in Python - Getting some real work done
    ( Page 4 of 8 )

    Our little example script above didn't accomplish much real work, of course, but it was helpful (I hope) in making sure your web server is set up to run Python CGI scripts. Now we're going to delve into the nitty-gritty of writing a real CGI program in Python. It might be helpful to have the Python tutorial open in another window to refer to from time to time on matters of syntax or keywords.

    The first thing that most web developers will want to know is how to get information out of HTML forms and do something with it.

    Python provides an excellent module to deal with this situation. Coincidentally enough, the module is named cgi. So let me show you a simple example program that will gather information out of a browser form.

    As you know, the data in HTML forms is referenced by the "name" attribute of each input element. For instance, this tag in a form: <INPUT TYPE=TEXT NAME=email SIZE=40> produces a 40 character wide text box with word "email" associated with it.

    This information is passed to a CGI script by either one of two methods: GET or POST. However, the cgi module hides this complexity from the programmer and presents all form information as a Python fundamental data type; the ever-useful dictionary. Perl users will know this one as a "hash" (which sounds like more fun than a dictionary, but the word is less descriptive.) A dictionary is a type of array that is indexed by a string instead of a number.

    For instance, if we had defined a dictionary called Bestiary, we could type something like this:


    >>> Bestiary["Zebra"]

    and Python might respond with:


    "A black and white striped ungulate native to southern Africa."

    [The little snippet above demonstrates an interesting and occasionally useful feature of Python: the ability to act as an interactive interpreter. ">>>" is the Python prompt. If you type an expression, as I did above, Python will print the return value. If you're only writing CGI scripts, you probably won't use the interactive interpreter much, but sometimes it does come in handy for debugging.]

    Python's cgi module has a method (another name for a procedure or function) called FieldStorage that returns a dictionary containing all the form <INPUT>'s and their corresponding values.

    If you know the specific item you want, you can easily access it:


    import cgi The_Form = cgi.FieldStorage() print The_Form["email"].value

    Note that just using The_Form["email"] returns a tuple containing both the field name and the value. When dealing with the dictionaries returned by cgi.FieldStorage, we need to be explicit in asking for the values in the forms.

    Any generic method that works on dictionaries can be usefully applied. For instance, if you want to find out which keys are available on any given form, you might do something like this:


    >>> The_Form.keys() ['name', 'email', 'address', 'phone']

    or this:


    >>> The_Form.values() ['Preston Landers', 'preston@askpreston.com', '1234 Main St.', '555-1212']

    (Please note that Python will not guarantee any particular order for the keys() or values() methods. If you want that, use sort())

    If you try to access a field that doesn't exist, this will generate an exception; an error status. If you don't catch the exception with an except: block, this will stop your script and the user will see the dreaded "Internal Server Error." Don't worry too much about it at this point because we'll be covering exceptions in great detail later on.

    We can put these pieces together to write a simple program that prints out the name and value of each <INPUT> element passed to it. In this case, it's up to you to provide an actual web page that contains the form that points to this CGI script as its ACTION field. If you're not sure what I mean, don't worry, we'll go over forms again.


    #!/usr/bin/python import cgi print "Content-Type: text/plain\n\n" The_Form = cgi.FieldStorage() for name in The_Form.keys(): print "Input: " + name + " value: " + The_Form[name].value + "<BR>" print "Finished!"

    As you can see, we used a simple for loop to iterate over each key, printing the key name, its value, and an HTML break to separate each line. Notice that blocks of code are set off by tabs in Python, not { } curlies like in C or Perl. When the indentation changes, as in the line that prints "Finished!," that signals the end of that code block.

    We've also demonstrated the + operation for strings; as you might expect, + will concatenate (stick together) two strings. If you're not sure if the elements you're concatenating will be strings at runtime, use the str() or repr() methods. For instance:


    >>> NumberA = 55 >>> NumberB = 45 >>> print NumberA + NumberB 100 >>> print str(NumberA) + str(NumberB) 5545


     
     
    >>> More Python Articles          >>> More By Preston Landers
     

       

    PYTHON ARTICLES

    - Tuples and Other Python Object Types
    - The Dictionary Python Object Type
    - String and List Python Object Types
    - Introducing Python Object Types
    - Mobile Programming using PyS60: Advanced UI ...
    - Nested Functions in Python
    - Python Parameters, Functions and Arguments
    - Python Statements and Functions
    - Statements and Iterators in Python
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT