1
Chapter 28 - Python
Outline
28.1
28.2
28.3
28.4
28.5
28.6
28.7
28.8
28.9
28.10
28.11
Introduction
Basic Data Types, Control Structures and Functions
Tuples, Lists and Dictionaries
String Processing and Regular Expressions
Exception Handling
Introduction to CGI Programming
Form Processing and Business Logic
Cookies
Database Application Programming Interface (DB-API)
Operator Precedence Chart
Internet and World Wide Web Resources
 2001 Prentice Hall, Inc. All rights reserved.
2
1
2
3
4
Outline
# Fig. 28.1: fig28_01.py
# A first program in Python
print "Welcome to Python!"
Welcome to Python!
Single-line comments.
Fig28_01.pv
The print statement to write the text
Program Output
Welcome to Python! to the screen.
 2001 Prentice Hall, Inc.
All rights reserved.
3
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> print "Welcome to Python!"
Welcome to Python!
>>> ^Z
Outline
Fig. 28.2 Python in interactive mode.
 2001 Prentice Hall, Inc.
All rights reserved.
4
28.2 Basic Data Types, Control Structures
and Function
Pytho n keyw ord s
and
continue
assert
def
break
del
class
elif
Fig. 28.3 Pytho n ke yw o rd s.
else
for
import
not
raise
except
exec
finally
from
global
if
in
is
lambda
or
pass
print
return
try
while
 2001 Prentice Hall, Inc. All rights reserved.
5
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> import keyword
>>> print keyword.kwlist
['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is','lambda', 'not', 'or', 'pass', 'print', 'raise',
'return', 'try', 'while']
>>>
Outline
Fig. 28.4 Printing Python keywords in interactive mode.
 2001 Prentice Hall, Inc.
All rights reserved.
6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Fig. 28.5: fig28_05.py
# Program to illustrate basic data types, control structures and
# functions.
The code in the while block executes as long
Outline
as
gcd is greater than or equal to 1.
Fig28_05.pv
modulo operator (%) determines if
parameters x and y can be divided evenly by
variable gcd.
def greatestCommonDivisor( x, y ):
The
gcd = min( x, y )
while gcd >= 1:
if ( x % gcd ) == ( y % gcd ) == 0:
return gcd
Function determineColor takes parameter color,
else:
The contains
returna string.
keyword exits the function and
which
gcd -= 1
returns the specified value.
def determineColor( color ):
if color == "green":
The comma
(,) (\)
thatatfollows
string
The backslash
character
the end the
of line
27 isinforms
a
print "You entered green!"
elif color == "purple":
Python thatcharacter
we want that
to print
additional
items after
line-continuation
allows
a statement
Function raw_input
to
get input
from thetouser.
print "You entered purple!"
theon
string.
continue
the next line.
else:
print "You did not enter green or purple."
number1 = int( raw_input( "Enter a positive integer: " ) )
Theinteger:
call to "Python
number2 = int( raw_input( "Enter a positive
) )
function range with an
argument of 5 returns the values 0, 1, 2, 3 and 4.
print "The greatest common divisor is", \
greatestCommonDivisor( number1, number2 )
for entry in range( 5 ):
colorChoice = raw_input( "\nEnter your favorite color: " )
determineColor( colorChoice )
 2001 Prentice Hall, Inc.
All rights reserved.
7
Enter a positive integer: 2
Enter a positive integer: 30
The greatest common divisor is 2
Outline
Program Output
Enter your favorite color: yellow
You did not enter green or purple.
Enter your favorite color: green
You entered green!
Enter your favorite color: black
You did not enter green or purple.
Enter your favorite color: purple
You entered purple!
Enter your favorite color: red
You did not enter green or purple.
 2001 Prentice Hall, Inc.
All rights reserved.
8
28.3 Tuples, Lists and Dictionaries
Esc a p e seq ue nc e
Mea ning
\n
\r
\t
\'
\"
\b
\\
Fig. 28.6 Esc a p e
Newline (line feed).
Carriage return.
Tab.
Single quote.
Double quote.
Backspace.
Backslash.
se q ue nc e s.
 2001 Prentice Hall, Inc. All rights reserved.
9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Fig. 28.7: fig28_07.py
A tuple, tuples,
with elements
"a"
and 3.0.
# A program that illustrates
lists 1,
and
dictionaries.
# tuples
aTuple = ( 1, "a", 3.0 )
firstItem = aTuple[ 0 ]
secondItem = aTuple[ 1 ]
thirdItem = aTuple[ 2 ]
#
#
#
#
firstItem,
print "The
print "The
print "The
print
Fig28_07.pv
create tuple
first tuple item
second tuple item
third tuple item
Unpack the
print "The first item in the tuple is", firstItem
print "The second item in the tuple is", secondItem
print "The third item in the tuple is", thirdItem
print
Outline
items of the tuple into three variables.
secondItem, thirdItem = aTuple
first item in the tuple is", firstItem
second item in the tuple is", secondItem
third item in the tuple is", thirdItem
A one-element tuple or singleton.
aTuple += ( 4, )
print "Used the += statement on the tuple"
print
# print the tuple
print "The raw tuple data is:", aTuple
print "The items in the tuple are:"
for item in aTuple:
print item,
print
print
The print statement handles a variable
that is a tuple.
# print each item
# end previous line
# blank line
 2001 Prentice Hall, Inc.
All rights reserved.
10
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# lists
aList = [ 1, 2, 3 ]
aList[ 0 ] = 0
aList.append( 5 )
# create list
# change first element of list
# add item to end of list
Outline
Fig28_07.pv
print "The raw list data is:", aList
# print list data
A
list
that
2 andan3. element
print
Calling listcontains
methodelements
append1,adds
to the
of a0end
list.
Theend
is assigned
to the element in the list at index 0.
item
tovalue
the
of the list
aList += [ 4 ]
# add an
print "Added an item to the list using the += statement"
print
# print each item in the list
print "The items in the list are:"
for item in aList:
print item,
print
print
# end previous line
# blank line
A Python dictionary.
Add a new element to a dictionary by using the []
Each
value in the dictionary is accessed using the []
operator.
operator
# dictionaries
aDictionary = { 1 : "January", 2 : "February", 3 : "March",
4 : "April", 5 : "May", 6 : "June", 7 : "July",
8 : "August", 9 : "September", 10 : "October",
11 : "November" }
aDictionary[ 12 ] = "December"
# add item to dictionary
print "The raw dictionary data is:", aDictionary
print "\nThe entries in the dictionary are:"
for item in aDictionary.keys():
print "aDictionary[ ", item, " ] = ", aDictionary[ item ]
 2001 Prentice Hall, Inc.
All rights reserved.
11
The first item in the tuple is 1
The second item in the tuple is a
The third item in the tuple is 3.0
Outline
Program Output
The first item in the tuple is 1
The second item in the tuple is a
The third item in the tuple is 3.0
Used the += statement on the tuple
The raw tuple data is: (1, 'a', 3.0, 4)
The items in the tuple are:
1 a 3.0 4
The raw list data is: [0, 2, 3, 5]
Added an item to the list using the += statement
The items in the list are:
0 2 3 5 4
The raw dictionary data is: {12: 'December', 11: 'November', 10:
'October', 9: 'September', 8: 'August', 7: 'July', 6: 'June', 5: 'May',
4: 'April', 3: 'March', 2: 'February', 1: 'January'}
 2001 Prentice Hall, Inc.
All rights reserved.
12
The entries in the dictionary are:
aDictionary[ 12 ] = December
aDictionary[ 11 ] = November
aDictionary[ 10 ] = October
aDictionary[ 9 ] = September
aDictionary[ 8 ] = August
aDictionary[ 7 ] = July
aDictionary[ 6 ] = June
aDictionary[ 5 ] = May
aDictionary[ 4 ] = April
aDictionary[ 3 ] = March
aDictionary[ 2 ] = February
aDictionary[ 1 ] = January
Outline
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
13
28.3 Tuples, Lists and Dictionaries
Me thod
Purp o se
append( item )
Inserts item at the end of the list.
count( item )
extend( newList )
index( item )
Returns the number of occurrences of item in the list.
insert( index, item )
pop( [index] )
Inserts item at position index.
remove( item )
Removes the first occurrence of item from the list. If item is not in the list, a
ValueError exception occurs.
Reverses the items in the list.
reverse()
sort( [function] )
Inserts newList at the end of the list.
Returns the index of the first occurrence of item in the list. If element is not in the list, a
ValueError exception occurs. [Note: We discuss exceptions in Section 28.5]
Removes and returns the last element in the list. If parameter index is specified, removes and
returns the element at position index.
Sorts items of the list. Optional parameter function is a comparison function that may be userdefined.
Fig. 28.8 Pytho n list m e tho d s.
 2001 Prentice Hall, Inc. All rights reserved.
14
28.3 Tuples, Lists and Dictionaries
Me thod
De sc rip tio n
clear()
Deletes all items from the dictionary.
copy()
get( key [, falseValue] )
Creates a copy of the dictionary.
has_key( key )
Returns 1 if key is in the dictionary; returns
items()
keys()
setdefault( key [, falseValue] )
Returns a list of tuples that are key-value pairs.
update( otherDictionary )
Adds all key-value pairs from otherDictionary to the current dictionary.
values()
Fig. 28.9 Dic tio na ry m e tho d s.
Returns a list of values in the dictionary.
 2001 Prentice Hall, Inc. All rights reserved.
Returns the value associated with key. If key is not in the dictionary and if
falseValue is specified, returns the specified value.
0 if key is not in the dictionary.
Returns a list of keys in the dictionary.
Behaves similarly to method get. If key is not in the dictionary and
falseValue is specified, inserts the key and the specified value into dictionary.
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Outline
# Fig. 28.10: fig28_10.py
# Program to illustrate use of strings
# simple string assignments
string1 = "This is a string."
print string1
The operator + concatenates the three strings
Fig28_10.py
string1, " " and string2.
string2 = "This is a second string."
print string2
# string concatenation
string3 = string1 + " " + string2
print string3
The *= statement concatenates string4 to itself
10 times.
Double quotes are displayed using the
Pythoncharacter
strings may
escape
(\).be contained either within
string4
double quotes or single quotes.
# using operators
string4 = '*'
print "String with an asterisk: " +
string4 *= 10
print "String with 10 asterisks: " + string4
# using quotes
print "This is a string with \"double quotes.\""
print 'This is another string with "double quotes."'
print 'This is a string with \'single quotes.\''
print "This is another string with 'single quotes.'"
print """This string has "double quotes" and 'single quotes.'"""
# string formatting
name = raw_input( "Enter your name: " )
age = raw_input( "Enter your age: " )
print "Hello, %s, you are %s years old." % ( name, age )
 2001 Prentice Hall, Inc.
All rights reserved.
16
This is a string.
This is a second string.
This is a string. This is a second string.
String with an asterisk: *
String with 10 asterisks: **********
This is a string with "double quotes."
This is another string with "double quotes."
This is a string with 'single quotes.'
This is another string with 'single quotes.'
This string has "double quotes" and 'single quotes.'
Enter your name: Brian
Enter your age: 33
Hello, Brian, you are 33 years old.
Outline
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
17
28.4 String Processing and Regular
Expressions
Sym b ol
Mea ning
c
Single character (i.e., a string of length one).
s
d
u
o
x
X
f
e, E
g, G
Fig. 28.11
String.
Signed decimal integer.
Unsigned decimal integer.
Unsigned octal integer.
abcdef).
Unsigned hexadecimal integer (using format ABCDEF).
Unsigned hexadecimal integer (using format
Floating-point number.
Floating-point number (using scientific notation).
Floating-point number (using least-significant digits).
String -fo rm a t c ha ra c te rs.
 2001 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#
#
The re module’s compile function
Fig. 28.12: fig28_12.py
re (regular
expression)
Program searches a Import
string the
using
the
regular
module.
compiles
the expression
regularmodule.
expression
"Test“.
import re
18
Outline
Fig28_12.py
searchString = "Testing pattern matches"
expression1
expression2
expression3
expression4
expression5
=
=
=
=
=
re.compile(
re.compile(
re.compile(
re.compile(
re.compile(
r"Test" )
r"^Test" )
r"Test$" )
r"\b\w*es\b" )
r"t[aeiou]", re.I )
if expression1.search( searchString ):
print '"Test" was found.'
if expression2.match( searchString ):
print '"Test" was found at the beginning of the line.'
if expression3.match( searchString ):
print '"Test" was found at the end of the line.'
result = expression4.findall( searchString )
if result:
print 'There are %d words(s) ending in "es":' % \
( len( result ) ),
for item in result:
print " " + item,
print
result = expression5.findall( searchString )
 2001 Prentice Hall, Inc.
All rights reserved.
19
35
36
37
38
39
40
41
42
if result:
print 'The letter t, followed by a vowel, occurs %d times:' % \
( len( result ) ),
for item in result:
print " " + item,
Outline
Fig28_12.py
print
 2001 Prentice Hall, Inc.
All rights reserved.
20
28.4 String Processing and Regular
Expressions
C ha ra c ter
Ma tc hes
^
Beginning of string.
$
.
*
+
?
{m, n}
\b
\B
\d
\D
\w
[...]
[^...]
Fig. 28.13
End of string.
Any character, except a newline.
Zero or more occurrences of the pattern.
One or more occurrences of the preceding pattern.
Zero or one occurrences of the preceding pattern.
Between m and n occurrences of the preceding pattern.
Word boundary (i.e., the beginning or end of a word).
Non-word boundary.
Digit ([0–9]).
Non-digit.
Any alpha-numeric character.
Any character defined by the set.
Any character not defined by the set.
So m e o f the
re m o d ule ’ s re g ula r e xp re ssio n c ha ra c te rs.
 2001 Prentice Hall, Inc. All rights reserved.
21
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>>
Outline
Fig. 28.14 Interactive session illustrating a ZeroDivisionError exception.
 2001 Prentice Hall, Inc.
All rights reserved.
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Fig. 28.15: fig28_15.py
# A simple program that illustrates exceptions.
def getFloat():
return float( raw_input( "Enter a number: " ) )
number1 = number2 = None
Outline
Fig28_15.py
Any code in the try block that raises an exception
will be “caught” and handled in the corresponding
except block
while number1 == None:
try:
number1 = getFloat()
except ValueError:
print "Value entered was not a number"
while number2 == None:
try:
number2 = getFloat()
except ValueError:
print "Value entered was not a number"
Print the results of dividing variables
number1 and number2.
try:
result = number1 / number2
except ZeroDivisionError:
print "Cannot divide by zero!"
else:
print "The result of division is: %f" % result
 2001 Prentice Hall, Inc.
All rights reserved.
23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!c:\Python\python.exe
# Fig 28.16: fig28_16.py
The cgi module provides
# Program to display CGI environment variables
functionalities for
writing CGI scripts.
Outline
Fig28_16.py
import os
import cgi
print "Content-type: text/html"
print
print """<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">"""
The environ data member of module
os holds all the environment variables.
print """
<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">
<head><title>Environment Variables</title></head>
<body><table style = "border: 0">"""
rowNumber = 0
for item in os.environ.keys():
rowNumber += 1
Function cgi.escape formats text in an “XHTML-safe”
way.
if rowNumber % 2 == 0:
backgroundColor = "white"
else:
backgroundColor = "lightgrey"
print """<tr style = "background-color: %s">
<td>%s</td><td>%s</td></tr>""" \
% ( backgroundColor, item,
cgi.escape( os.environ[ item ] ) )
 2001 Prentice Hall, Inc.
All rights reserved.
24
36
print """</table></body></html>"""
Outline
Fig28_16.py
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<!-- Fig. 28.17: fig28_17.html -->
Outline
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>
The form element specifies how the information enclosed
by tags <form> and </form> should be handled.
<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 />
 2001 Prentice Hall, Inc.
All rights reserved.
26
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<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>
Outline
Fig28_17.html
<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
checked = "checked" />
Windows NT
<input type = "radio" name
Windows 2000
<input type = "radio" name
Windows 95/98/ME<br />
<input type = "radio" name
= "os" value = "Windows NT"
= "os" value = "Windows 2000" />
= "os" value = "Windows 95_98" />
= "os" value = "Linux" />
 2001 Prentice Hall, Inc.
All rights reserved.
27
68
69
70
71
72
73
74
75
Linux
<input type = "radio" name = "os" value = "Other" />
Other<br />
<input type = "submit" value = "Register" />
Outline
Fig28_17.html
</form>
</body>
</html>
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!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.
Outline
Fig28_18.py
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">
 2001 Prentice Hall, Inc.
All rights reserved.
29
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<tr><td
<td
<td
<td
style
style
style
style
=
=
=
=
"background-color:
"background-color:
"background-color:
"background-color:
yellow">Name </td>
yellow">Email</td>
yellow">Phone</td>
yellow">OS</td></tr>
Outline
Fig28_18.py
<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."""
 2001 Prentice Hall, Inc.
All rights reserved.
30
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
Outline
Call to function printContent.
printContent()
form = cgi.FieldStorage()
Fig28_18.py
try:
personInfo = { 'firstName' : form[ "firstname" ].value,
'lastName' : form[ "lastname" ].value,
'email' : form[ "email" ].value,
'phone' : form[ "phone" ].value,
Create
an
instance
'book' : form[ "book" ].value,
'os' : form[ "os" ].value }
FieldStorage and
except KeyError:
instance to variable form.
printFormError()
of
class
assigns the
if telephoneExpression.match( personInfo[ 'phone' ] ):
printReply()
else:
printPhoneError()
Function printFormError
prints a message in the
Function
the form
user has
and not been
browserprintReply
that tells the thanks
user the
displays
an XHTML
table
with
the information
completed
properly
and instructs
the
user to click the
Function
printPhoneError
displays
a message
Each value is accessed
via the
value
data
from
thetoinforms
form.
button
fill
outmember
the user
formthat
and the
resubmit
in gathered
theBack
browser
that
the
phoneit.
of a particular form
element.
number
is in improper format and instructs the user
to click the Back button to change the phone
number and resubmit the form.
 2001 Prentice Hall, Inc.
All rights reserved.
31
Outline
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<!-- Fig. 28.19: fig28_19.html -->
Outline
Fig28_19.html
<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang = "en"
lang = "en">
<head>
<title>Writing a cookie to the client computer</title>
</head>
<body style = "background-image: images/back.gif;
font-family: Arial,sans-serif; font-size: 11pt" >
<span style = "font-size: 15pt; font-weight: bold">
Click Write Cookie to save your cookie data.
</span><br />
<form method =
<span style
<input type
<span style
<input type
<span style
<input type
<input type
</form>
"post" action = "/cgi-bin/fig28_20.py">
= "font-weight: bold">Name:</span><br />
= "text" name = "name" /><br />
= "font-weight: bold">Height:</span><br />
= "text" name = "height" /><br />
= "font-weight: bold">Favorite Color</span><br />
= "text" name = "color" /><br />
= "submit" value = "Write Cookie" />
</body>
</html>
 2001 Prentice Hall, Inc.
All rights reserved.
33
Outline
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!C:\Python\python.exe
# Fig. 28.20: fig28_20.py
# Writing a cookie to a client's
Functionmachine
printContent
import cgi
import Cookie
import time
Outline
prints the content header and
XHTML DOCTYPE string to the browser.
Fig28_20.py
def printContent():
print "Content-type: text/html"
Retrieve the form values by using
print
print """
class FieldStorage from module
<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en"
cgi.
lang="en">
<head><title>Cookie values</title></head>"""
form = cgi.FieldStorage()
# get form information
try: # extract form values
name = form[ "name" ].value
height = form[ "height" ].value
color = form[ "color" ].value
except KeyError:
printContent()
print """<body><h3>You have not filled in all fields.
<span style = "color: blue"> Click the Back button,
fill out the form and resubmit.<br /><br />
Thank You. </span></h3>"""
else:
 2001 Prentice Hall, Inc.
All rights reserved.
35
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Outline
# construct cookie expiration date and path
expirationFormat = "%A, %d-%b-%y %X %Z"
expirationTime = time.localtime( time.time() + 300 )
expirationDate = time.strftime( expirationFormat,
expirationTime )
Specifie the format for
path = "/"
# construct cookie contents
cookie = Cookie.Cookie()
Fig28_20.py
the expiration value of the
cookie.
the strftime
function
toCookie.
format
a time tuple
The timeCall
function
of
time
returns
a floating-point
Creates
anmodule
instance
of class
a string.
value thatinto
is the
number of seconds since the epoch (i.e.,
January 1, 1970).
cookie[ "Name" ] = name
cookie[ "Name" ][ "expires" ] = expirationDate
cookie[ "Name" ][ "path" ] = path
cookie[ "Height" ] = height
cookie[ "Height" ][ "expires" ] = expirationDate
cookie[ "Height" ][ "path" ] = path
cookie[ "Color" ] = color
cookie[ "Color" ][ "expires" ] = expirationDate
cookie[ "Color" ][ "path" ] = path
Set the values for the cookie
based on the user-entered values
retrieved from the XHMTL
form.
# print cookie to user and page to browser
print cookie
printContent()
print """<body style = "background-image: /images/back.gif;
font-family: Arial,sans-serif; font-size: 11pt">
The cookie has been set with the following data: <br /><br />
<span style = "color: blue">Name:</span> %s<br />
<span style = "color: blue">Height:</span> %s<br />
<span style = "color: blue">Favorite Color:</span>
<span style = "color: %s"> %s</span><br />""" \
% ( name, height, color, color )
 2001 Prentice Hall, Inc.
All rights reserved.
36
66
67
68
69
70
print """<br /><a href= "fig28_21.py">
Read cookie values</a>"""
print """</body></html>"""
Outline
Fig28_20.py
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!C:\Python\python.exe
# Fig. 28.21: fig28_21.py
# Program that retrieves and displays client-side cookie values
import Cookie
import os
print "Content-type: text/html"
print
print """
The load method
of class Cookie
<html xmlns = "http://www.w3.org/1999/xhtml"
xml:lang="en"
lang="en">
extracts cookie values from a string.
Retrieve the
<head><title>Cookie values</title></head>
<body style =
the client.
font-family: Arial, sans-serif; font-size: 11pt">"""
Outline
Fig28_21.py
cookie values from
try:
cookie = Cookie.Cookie()
cookie.load( os.environ[ "HTTP_COOKIE" ] )
If the program successfully retrieves
except KeyError:
cookie values, display the values in
print """<span style = "font-weight: bold">Error reading cookies
browser.
</span>"""
else:
print """<span style = "font-weight: bold">
The following data is saved in a cookie on your computer.
</span><br /><br />"""
the
the
print """<table style = "border-width: 5; border-spacing: 0;
padding: 10">"""
for item in cookie.keys():
print """<tr>
<td style = "background-color: lavender">%s</td>
<td style = "background-color: white">%s</td>
</tr>""" % ( item, cookie[ item ].value )
 2001 Prentice Hall, Inc.
All rights reserved.
38
36
37
38
39
print """</table>"""
print """</body></html>"""
Outline
Fig28_21.py
 2001 Prentice Hall, Inc.
All rights reserved.
39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!c:\Python\python.exe
Print the HTTP header
# Fig. 28.22: fig28_22.py
# A program to illustrate Python's database
connectivity.
string to
the browser.
import MySQLdb
Outline
and XHTML DOCTYPE
print "Content-type: text/html"
print
print """
<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en"
Connect to the
lang="en">
called books.
<head><title>Select Author</title></head>
<body style =
Call the cursor
font-family: Arial, sans-serif; font-size: 11pt">"""
Fig28_22.py
MySQL database
method of object
to return a Cursor object that
Method execute executes an SQL queryconnection
against
try:
execute queries against the database.
the database.= MySQLdb.connect( db = "books"
connection
)
except OperationalError:
print "Unable to connect to database: %s" % message
else:
cursor = connection.cursor()
Retrieve the results of the
cursor.execute( "SELECT * FROM Authors" )
calling method fetchall.
authorList = cursor.fetchall()
cursor.close()
connection.close()
query by
# close cursor
# close connection
print """
<form method = "post" action = "/cgi-bin/fig28_23.py">
<select name = "authorID">"""
for author in authorList:
print """<option value = %d>%s, %s</option>""" \
% ( author[ 0 ], author[ 2 ], author[ 1 ] )
print """
 2001 Prentice Hall, Inc.
All rights reserved.
40
36
37
38
39
40
</select>
<input type = "submit" value = "Execute Query" />
</ form>"""
print """</body></html>"""
Outline
Fig28_22.py
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
#!c:\Python\python.exe
# Fig. 28.23: fig28_23.py
# A program to illustrate Python's database connectivity.
Fig28_23.py
import cgi
import MySQLdb
import sys
# get results from form
form = cgi.FieldStorage()
print "Content-type: text/html"
print
print """
<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">
<head><title>Query results</title></head>
<body style =
font-family: Arial, sans-serif; font-size: 11pt">"""
try:
authorID = form[ "authorID" ].value
except KeyError:
Connect to the MySQL database
print """<span style = "color: red size = 15pt">
called books.
FORM ERROR</span><br />
You did not select an author.<br />
<span style = "color: blue"> Click the Back button,
fill out the form and resubmit.<br /><br />
Thank You.</span></body></html>"""
Function sys.exit causes the
sys.exit()
program to terminate.
# connect to database and get cursor
try:
connection = MySQLdb.connect( db = 'books' )
except OperationalError:
 2001 Prentice Hall, Inc.
All rights reserved.
42
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
print """<span style = "color: red size = 15pt">
DATABASE ERROR</span><br /> Unable to connect to database.
</body></html>"""
sys.exit()
Outline
Fig28_23.py
queryString = """select Titles.* from Titles, AuthorISBN
where AuthorISBN.AuthorID=%s and
Titles.ISBN=AuthorISBN.ISBN""" % authorID
cursor = connection.cursor()
cursor.execute( queryString )
results = cursor.fetchall()
cursor.close()
connection.close()
Construct a query string to execute
Retrieve the results of the query using
against the database.
and and
storeexecute
the records
Create method
a cursor fetchall
for the database
the query
in localthe
variable
results
closestring
cursor
against
database.
#
# close connection
# display results
print """<table style = "border: groove 2 pt;
border-colapse: separate">
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Edition</th>
<th>Year</th>
<th>Description</th>
<th>Publisher ID</th>
</tr>"""
for row in results:
print "<tr>"
for entry in row:
print '<td style = "border: solid 2pt">%s</td>' % entry
 2001 Prentice Hall, Inc.
All rights reserved.
43
71
72
73
print "</tr>"
Outline
print """</table></body></html>"""
Fig28_23.py
Program Output
 2001 Prentice Hall, Inc.
All rights reserved.
44
28.10 Operator Precedence Chart
Op era tor
Typ e
Assoc ia tivity
‘ ‘
string conversion
left to right
{ }
[ ]
( )
( )
[ : ]
[ ]
.
**
~
+
*
/
%
+
Fig. 28.24
dictionary creation
left to right
list creation
left to right
tuple creation or expression grouping
left to right
function call
left to right
slicing
left to right
subscript access
left to right
member access
left to right
exponentiation
right to left
bitwise NOT
left to right
unary plus
unary minus
right to left
multiplication
division
modulus (remainder)
left to right
addition
subtraction
left to right
Python op era tor p rec ed enc e c ha rt.
 2001 Prentice Hall, Inc. All rights reserved.
45
28.10 Operator Precedence Chart
Op era tor
Typ e
Assoc ia tivity
<<
>>
&
^
|
<
<=
>
>=
!=
==
is, is not
in, not in
not
left shift
right shift
left to right
bitwise AND
left to right
bitwise XOR
left to right
bitwise OR
left to right
less than
less than or equal
greater than
greater than or equal
not equal
equal
left to right
identity
left to right
membership tests
left to right
boolean NOT
left to right
and
or
lambda
Fig. 28.24
boolean AND
left to right
boolean OR
left to right
lambda expressions (anonymous functions)
left to right
Python op era tor p rec ed enc e c ha rt.
 2001 Prentice Hall, Inc. All rights reserved.