Chapter: Internet & World Wide Web HOW TO PROGRAM - Python

Form Processing and Business Logic - Python

XHTML forms allow users to enter data to be sent to a Web server for processing. Once the server receives the form, a server program processes the data.

Form
Processing and Business Logic

XHTML forms allow users to enter data to be sent to a Web server for
processing. Once the server receives the form, a server program processes the
data. Such a program could help people purchase products, send and receive
Web-based e-mail, complete a survey, etc. These types of Web applications allow
users to interact with the server. Figure 28.17 uses an XHTML form to allow
users to input personal information for a mailing list. This type of
registration might be used to store user information in a database.

<!DOCTYPE html PUBLIC

"-//W3C//DTD XHTML 1.0 Transitional//EN"

"DTD/xhtml1-transitional.dtd">

<!-- Fig. 28.17: fig28_17.html -->

<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en"

lang="en">

<head>

<title>Sample FORM to take user input in HTML</title>

</head>

<body style = "font-family: Arial, sans-serif;
font-size: 11pt">

<div style = "font-size: 15pt; font-weight: bold">

This
is a sample registration form.

</div>

Please
fill in all fields and click Register.

<form method = "post" action = "/cgi-bin/fig28_18.py">

<img src = "images/user.gif" alt = "user" /><br />

<div style = "color: blue">

Please
fill out the fields below.<br />

</div>

<img src = "images/fname.gif" alt = "firstname" />

<input type = "text" name = "firstname" /><br />

<img src = "images/lname.gif" alt = "lastname" />

<input type = "text" name = "lastname" /><br />

<img src = "images/email.gif" alt = "email" />

<input type = "text" name = "email" /><br />

<img src = "images/phone.gif" alt = "phone" />

<input type = "text" name = "phone" /><br />

<div style = "font-size: 8pt">

Must
be in the form (555)555-5555<br/><br/>

</div>

<img src = "images/downloads.gif" alt = "downloads" /><br />

<div style = "color: blue">

Which
book would you like information about?<br />

</div>

<select name =
"book">

<option>XML How to Program</option>

<option>Python How to Program</option>

<option>E-business and E-commerce How to
Program</option>

<option>Internet
and WWW How to Program 2e</option>

<option>C++ How to Program 3e</option>

<option>Java How to
Program 4e</option>

<option>Visual Basic How to Program</option>

</select>

<br /><br />

<img src = "images/os.gif" alt = "os" /><br />

<div style = "color: blue">

Which operating system are you

currently
using?<br />

</div>

<input type = "radio" name = "os" value = "Windows NT"

checked = "checked" />

Windows
NT

<input type = "radio" name = "os" value = "Windows 2000" />

Windows
2000

<input type = "radio" name = "os" value = "Windows 95_98" />

Windows
95/98/ME<br />

<input type = "radio" name = "os" value = "Linux" />

Linux

<input type = "radio" name = "os" value = "Other" />

Other<br />

<input type = "submit" value = "Register" />

</form>

</body>

</html>

Fig. 28.17 XHTML form to
collect information from user

The form element
(line 19) specifies how the information enclosed by tags <form> and </form> should
be handled. The first attribute, method
= "post", directs the browser to send the
form’s information to the server. The second attribute, action = "/cgi-bin/fig28_18.py", directs the server to execute the fig28_18.py Pythonscript,
located in the cgi-bin directory. The names given to the input items (e.g., firstname) in the
Web page are important when the Python script is executed on theserver.
These names allow the script to refer to the individual pieces of data the user
sub-mits. When the user clicks the button labeled Register, both the input items and the names given to the items are sent to the fig28_18.py Python
script.

Figure 28.18 takes user information from fig28_17.html and
sends a Web page to the client indicating that the information was received.
Line 6 imports the cgi module, which provides functionality for writing CGI scripts in Python,
including access to XHTML form values.

#!c:\Python\python.exe

# Fig. 28.18: fig28_18.py

# Program to read information sent to the server from the

# form in the form.html document.

import cgi

import re

# the regular expression for matching most US phone numbers

telephoneExpression
= \

re.compile(
r'^\(\d{3}\)\d{3}-\d{4}$' )

def printContent():

print "Content-type: text/html"

print

print """

<html xmlns = "http://www.w3.org/1999/xhtml"
xml:lang="en"

lang="en">

<head><title>Registration
results</title></head>

<body>"""

def printReply():

print """

Hi <span
style = "color: blue; font-weight: bold">

%(firstName)s</span>.

Thank you for
completing the survey.<br />

You have been
added to the <span style = "color: blue;

font-weight:
bold">%(book)s </span> mailing list.<br /><br />

<span
style = "font-weight: bold">

The following
information has been saved in our database:

</span><br
/>

<table style
= "border: 0; border-width: 0;

border-spacing: 10">

<tr><td style =
"background-color: yellow">Name </td>

<td style =
"background-color: yellow">Email</td>

<td style = "background-color:
yellow">Phone</td>

<td style = "background-color:
yellow">OS</td></tr>

<tr><td>%(firstName)s
%(lastName)s</td><td>%(email)s</td>

<td>%(phone)s</td><td>%(os)s</td></tr>

</table>

<br /><br /><br />

<div style = "text-align: center; font-size:
8pt">

This is only a sample form.

You have not been added to a mailing list.

</div></center>

""" % personInfo

def printPhoneError():

print """<span style = "color: red; font-size
15pt">

INVALID PHONE NUMBER</span><br />

A valid phone number must be in the form

<span style = "font-weight:
bold">(555)555-5555</span>

<span style = "color: blue"> Click the Back
button,

enter a valid phone number and resubmit.</span><br
/><br />

Thank You."""

def printFormError():

print """<span style = "color: red; font-size
15pt">

FORM ERROR</span><br />

You have not filled in all fields.

<span style = "color: blue"> Click the Back
button,

fill out the form and resubmit.</span><br /><br
/>

Thank You."""

printContent()

form = cgi.FieldStorage()

try:

personInfo = { 'firstName' : form[
"firstname" ].value,

'lastName' : form[ "lastname"
].value,

'email'
: form[ "email" ].value,

'phone'
: form[ "phone" ].value,

'book'
: form[ "book" ].value,

'os'
: form[ "os" ].value }

except
KeyError:

printFormError()

if
telephoneExpression.match( personInfo[ 'phone' ] ):

printReply()

else:

printPhoneError()

Fig. 28.18 XHTML form to
get cookie values from user

Line 72 begins the main portion
of the script and calls function printContent to print the proper HTTP header and XHTML DOCTYPE string.
Line 74 creates an instance of class FieldStorage and
assigns the instance to variable form. This class contains information about any posted forms. The try block
(lines 76–82) creates a dictionary that contains the appropriate values from
each defined element in form. Each value is accessed via the valuedata member of a particular form element.
For example, line 78 assigns the value of the lastName field of form to the dictionary key 'lastName'.

If the value of any element in form is None, the try block
raises a KeyError exception, and we call function printFormError. This
function (lines 63–70) prints a message in the browser that tells the user the
form has not been completed properly and instructs the user to click the Back button to fill out the form and
resubmit it.

Line 86 tests the user-submitted
phone number against the specified format. We com-pile the regular expression telephoneExpression in lines 10–11. If the expression’s match method
does not return
None, we call the printReply function
(discussedmomentarily). If the match method does return None (i.e., the phone number is not in the proper format), we call function printPhoneError. This
function (lines 53–61) dis-plays a message in the browser that informs the user
that the phone number is in improper format and instructs the user to click the
Back button to
change the phone number and resubmit the form.

If the user has filled out the
form correctly, we call function printReply (lines 22– 51). This function thanks the user and displays an XHTML table with the
information gathered from the form. Notice that we format the output with
values from the person-Info
dictionary. For example, the beginning of line 25

%(firstName)s

inserts the value of the string variable firstName into the
string after the percent sign (%). Line 51 informs Python that the string variable firstName is a key
in the dictionary personInfo. Thus, the text at the beginning of line 25 is replaced with the value
storedin personInfo['firstName'].