Python on the Web (
Page 1 of 6 )
Python’s flexible nature means it can bend to almost any application you can
imagine and web development is no exception. This article covers simple form
handling and creating cookies and presents an example using everything
demonstrated.
If you've ever seen Python in action, even at a distance, I'm sure you'll
agree that it looks pretty neat. And the combination of development speed,
out-of-the-box power, and stunning syntax usually means you end up with one
thing... elegant, maintainable solutions, quickly. And lets face it, that's just
what web developers are looking for right?
I'll let you judge for yourself...
In this article we're going to be using Python to write some small and
(hopefully) interesting examples, starting with simple form handling and ending
with a complete, full featured (upload limit, file types etc.) upload script
that you can use in your websites!
If you haven't guessed it already this is a Python article, so if you're new
to the language I highly recommend reading Martin Tsachev's Getting
Started with Python before reading this one. if you need a quick
intro to Python CGI, skim over Preston Landers' "Writing
CGI Programs in Python".
Before we get going, you'll need a few things before you can run the examples
in this article:
1. A web server set up to handle CGI (tested with Apache)
2. The latest
version of Python from www.python.org
Creating a Form to Display User Details
Possibly the most important thing a web application does is collect user
input. And like most things, Python has just the module we need in its Standard
Library.
Let's jump right in and write a small function to display the user's details
if any where entered. (For this we'll assume our form looks like this... three
input boxes called - 'name', 'age' and 'email'. A check box called 'done' and a
'submit' button)
#!/usr/bin/env python
import cgi
form = cgi.FieldStorage()
def values(fields):
for
value in fields:
if value in form: print form[value].value +
'<br />'
if __name__ ==
'__main__':
print 'Content-Type: text/htmln'
if 'submit' and 'done' in
form:
values(('name', 'age',
'email'))
else:
print 'if you were directed here in
error please visit here.com'
This is very simple but it gives you an idea of how easy working with
forms is when you strip away all the crap!
In this example (and most of the examples in this article) we start by
importing the 'cgi' module and creating an instance of the FieldStorage() class to store our form
values. Next we define a new user function called values() which takes a sequence of
field names and iterates over them, printing the value if the one was set.
Finally before the function outputs anything we check if the 'submit' and 'done'
fields exist.
Ok, chances are you noticed this but just for clarity: forms in Python work
like any dictionary, with the exception that you have to follow the call by the
variable you want access from that key i.e. form['key'].value gives you the
value.