Home arrow Python arrow Page 4 - Writing CGI Programs in Python

Getting some real work done - Python

And now for something completely different... Python has a very extensive, well documented and portable module library that provides a large variety of useful functions. The Internet-related collection is particularly impressive, with modules to deal with everything from parsing and retrieving URL's to retrieving mail from POP servers and everything in between.

TABLE OF CONTENTS:
  1. Writing CGI Programs in Python
  2. Why should my next CGI project be in Python?
  3. Your First CGI program in Python
  4. Getting some real work done
  5. Defining a useful Display function
  6. Putting the pieces together
  7. Simple Database Access
  8. Other Resources and Links
By: Preston Landers
Rating: starstarstarstarstar / 78
August 25, 1999

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- 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

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: