Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 35 – Python Outline 35.1 Introduction 35.1.1 First Python Program 35.1.2 Python Keywords 35.2 Basic Data Types, Control Statements and Functions 35.3 Tuples, Lists and Dictionaries 35.4 String Processing and Regular Expressions 35.5 Exception Handling 35.6 Introduction to CGI Programming 35.7 Form Processing and Business Logic 35.8 Cookies 35.9 Database Application Programming Interface (DB-API) 35.9.1 Setup 35.9.2 Simple DB-API Program 35.10 Operator Precedence Chart 35.11 Web Resources 2004 Prentice Hall, Inc. All rights reserved. Objectives • In this lesson, you will learn: – To understand basic Python data types. – To understand string processing and regular expressions in Python. – To use exception handling. – To perform basic CGI tasks in Python. – To construct programs that interact with MySQL databases using the Python Database Application Programming Interface (DB-API). 2004 Prentice Hall, Inc. All rights reserved. 35.1 Introduction • Python – – – – – – – – Interpreted Cross-platform Object-oriented Large-scale Internet search engines Small administration scripts GUI applications CGI scripts Freely distributed 2004 Prentice Hall, Inc. All rights reserved. 35.1.1 First Python Program • Python – Can be executed on a program stored in a file – Can run in interactive mode • Users enter lines of code one at a time • Enables programmers to test small blocks of code quickly 2004 Prentice Hall, Inc. All rights reserved. 1 # Fig. 35.1: fig35_01.py 2 # A first program in Python 3 4 Outline print "Welcome to Python!" Welcome to Python! fig35_01.py (1 of 1) 2004 Prentice Hall, Inc. All rights reserved. 35.1.1 First Python Program 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 Fig. 35.2 Python in interactive mode. 2004 Prentice Hall, Inc. All rights reserved. 35.1.2 Python Keywords • Python is case-sensitive • Keywords can be obtained from keyword module 2004 Prentice Hall, Inc. All rights reserved. 35.1.2 Python Keywords Python keywords and continue else assert def except break del exec class elif finally Fig. 35.3 Python keywords. for from global if import in is lambda not or pass print raise return try while 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'] >>> Fig. 35.4 Printing Python keywords in interactive mode. 2004 Prentice Hall, Inc. All rights reserved. 35.2 Basic Data Types, Control Statements and Functions • Introduces basic data types, control statements, and functions – while loop – if statement – Modulo operator ( % ) – return keyword – if…elif…else statement – Line-continuation character ( \ ) – Escape sequences 2004 Prentice Hall, Inc. All rights reserved. 1 # Fig. 35.5: fig35_05.py 2 # Program to illustrate basic data types, control structures and 3 # functions. Outline 4 5 6 def greatestCommonDivisor( x, y ): gcd = min( x, y ) fig35_05.py (1 of 2) 7 8 while gcd >= 1: 9 10 if ( x % gcd ) == ( y % gcd ) == 0: return gcd 11 12 else: gcd -= 1 13 14 15 def determineColor( color ): 16 17 18 19 20 21 22 if color == "green": print "You entered green!" elif color == "purple": print "You entered purple!" else: print "You did not enter green or purple." 23 24 number1 = int( raw_input( "Enter a positive integer: " ) ) 25 number2 = int( raw_input( "Enter a positive integer: " ) ) 2004 Prentice Hall, Inc. All rights reserved. 26 27 print "The greatest common divisor is", \ 28 greatestCommonDivisor( number1, number2 ) Outline 29 30 for entry in range( 5 ): 31 colorChoice = raw_input( "\nEnter your favorite color: " ) 32 determineColor( colorChoice ) fig35_05.py (2 of 2) Enter a positive integer: 2 Enter a positive integer: 30 The greatest common divisor is 2 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. 2004 Prentice Hall, Inc. All rights reserved. 35.2 Basic Data Types, Control Statements and Functions Meaning Escape sequence \n Newline (line feed). \r Carriage return. \t Tab. \' Single quote. \" Double quote. \b Backspace. \\ Backslash. Fig. 35.6 Escape sequences. 2004 Prentice Hall, Inc. All rights reserved. 35.3 Tuples, Lists and Dictionaries • list – A sequence of related data • Tuple – A list whose elements may not be modified – Immutable – Singleton • One-element tuple • Dictionary – A list of values that are accessed through their associated keys 2004 Prentice Hall, Inc. All rights reserved. 1 # Fig. 35.7: fig35_07.py 2 # A program that illustrates tuples, lists and dictionaries. Outline 3 4 # tuples 5 aTuple = ( 1, "a", 3.0 ) # create tuple 6 firstItem = aTuple[ 0 ] # first tuple item 7 secondItem = aTuple[ 1 ] # second tuple item 8 thirdItem = aTuple[ 2 ] # third tuple item fig35_07.py (1 of 3) 9 10 print "The first item in the tuple is", firstItem 11 print "The second item in the tuple is", secondItem 12 print "The third item in the tuple is", thirdItem 13 print 14 15 firstItem, secondItem, thirdItem = aTuple 16 print "The first item in the tuple is", firstItem 17 print "The second item in the tuple is", secondItem 18 print "The third item in the tuple is", thirdItem 19 print 20 21 aTuple += ( 4, ) 22 print "Used the += statement on the tuple" 23 print 24 2004 Prentice Hall, Inc. All rights reserved. 25 # print the tuple 26 print "The raw tuple data is:", aTuple Outline 27 print "The items in the tuple are:" 28 29 for item in aTuple: 30 # print each item print item, fig35_07.py (2 of 3) 31 32 print # end previous line 33 print # blank line 34 35 # lists 36 aList = [ 1, 2, 3 ] # create list 37 aList[ 0 ] = 0 # change first element of list 38 aList.append( 5 ) # add item to end of list 39 40 print "The raw list data is:", aList # print list data 41 print 42 43 aList += [ 4 ] # add an item to the end of the list 44 print "Added an item to the list using the += statement" 45 print 46 47 # print each item in the list 48 print "The items in the list are:" 49 2004 Prentice Hall, Inc. All rights reserved. 50 for item in aList: 51 print item, Outline 52 53 print # end previous line 54 print # blank line fig35_07.py (3 of 3) 55 56 # dictionaries 57 aDictionary = { 1 : "January", 2 : "February", 3 : "March", 58 4 : "April", 5 : "May", 6 : "June", 7 : "July", 59 8 : "August", 9 : "September", 10 : "October", 60 11 : "November" } 61 aDictionary[ 12 ] = "December" # add item to dictionary 62 63 print "The raw dictionary data is:", aDictionary 64 print "\nThe entries in the dictionary are:" 65 66 for item in aDictionary.keys(): 67 print "aDictionary[ ", item, " ] = ", aDictionary[ item ] 2004 Prentice Hall, Inc. All rights reserved. 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 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'} 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 2004 Prentice Hall, Inc. All rights reserved. 35.3 Tuples, Lists and Dictionaries Method append( item ) count( item ) extend( newList ) index( item ) insert( index, item ) pop( [index] ) Purpose Inserts item at the end of the list. Returns the number of occurrences of item in the list. Inserts newList at the end of the list. Returns the index of the first occurrence of item in the list. If the element is not in the list, a ValueError exception occurs. [Note: We discuss exceptions in Section 35.5] Inserts item at position index. Removes and returns the last element in the list. If parameter index is specified, removes and returns the element 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. reverse() Reverses the items in the list. sort( [function] ) Sorts the items in the list. Optional parameter function is a comparison function that may be user defined. Fig. 35.8 Python list methods. 2004 Prentice Hall, Inc. All rights reserved. 35.3 Tuples, Lists and Dictionaries Method clear() copy() get( key [, falseValue] ) has_key( key ) items() keys() setdefault( key [, falseValue] ) update( otherDictionary ) values() Fig. 35.9 Dictionary methods. 2004 Prentice Hall, Inc. All rights reserved. Description Deletes all items from the dictionary. Creates a copy of the dictionary. Returns the value associated with key. If key is not in the dictionary and if falseValue is specified, returns the specified value. Returns 1 if key is in the dictionary; returns 0 if key is not in the dictionary. Returns a list of tuples that are key-value pairs. 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 the dictionary. Adds all the key-value pairs from otherDictionary to the current dictionary. Returns a list of values in the dictionary. 35.4 String Processing and Regular Expressions • Regular expression – Used to search through strings, text files, databases, and so on • Regular-expression string – Defines a pattern with which text data can be compared 2004 Prentice Hall, Inc. All rights reserved. 1 # Fig. 35.10: fig35_10.py 2 # Program to illustrate use of strings Outline 3 4 # simple string assignments 5 string1 = "This is a string." 6 print string1 fig35_10.py (1 of 2) 7 8 string2 = "This is a second string." 9 print string2 10 11 # string concatenation 12 string3 = string1 + " " + string2 13 print string3 14 15 # using operators 16 string4 = '*' 17 print "String with an asterisk: " + string4 18 string4 *= 10 19 print "String with 10 asterisks: " + string4 20 21 # using quotes 22 print "This is a string with \"double quotes.\"" 23 print 'This is another string with "double quotes."' 24 print 'This is a string with \'single quotes.\'' 25 print "This is another string with 'single quotes.'" 2004 Prentice Hall, Inc. All rights reserved. 26 print """This string has "double quotes" and 'single quotes.'""" 27 28 # string formatting Outline 29 name = raw_input( "Enter your name: " ) 30 age = raw_input( "Enter your age: " ) 31 print "Hello, %s, you are %s years old." % ( name, age ) fig35_10.py (2 of 2) 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. 2004 Prentice Hall, Inc. All rights reserved. 35.4 String Processing and Regular Expressions Symbol c s d u o x X f e, E g, G Fig. 35.11 Meaning Single character (i.e., a string of length 1). String. Signed decimal integer. Unsigned decimal integer. Unsigned octal integer. Unsigned hexadecimal integer (using format abcdef). Unsigned hexadecimal integer (using format ABCDEF). Floating-point number. Floating-point number (using scientific notation). Floating-point number (using least-significant digits). String-format characters. 2004 Prentice Hall, Inc. All rights reserved. 1 # Fig. 35.12: fig35_12.py 2 # Program searches a string using the regular expression module. Outline 3 4 import re 5 6 searchString = "Testing pattern matches" fig35_12.py (1 of 2) 7 8 expression1 = re.compile( r"Test" ) 9 expression2 = re.compile( r"^Test" ) 10 expression3 = re.compile( r"Test$" ) 11 expression4 = re.compile( r"\b\w*es\b" ) 12 expression5 = re.compile( r"t[aeiou]", re.I ) 13 14 if expression1.search( searchString ): 15 print '"Test" was found.' 16 17 if expression2.match( searchString ): 18 print '"Test" was found at the beginning of the line.' 19 20 if expression3.match( searchString ): 21 print '"Test" was found at the end of the line.' 22 23 result = expression4.findall( searchString ) 24 2004 Prentice Hall, Inc. All rights reserved. 25 if result: 26 print 'There are %d words(s) ending in "es":' % \ ( len( result ) ), 27 Outline 28 29 for item in result: print " " + item, 30 fig35_12.py (2 of 2) 31 32 print 33 result = expression5.findall( searchString ) 34 35 if result: 36 print 'The letter t, followed by a vowel, occurs %d times:' % \ ( len( result ) ), 37 38 39 for item in result: 40 print " " + item, 41 42 print 2004 Prentice Hall, Inc. All rights reserved. 35.4 String Processing and Regular Expressions Character ^ $ . * + ? {m, n} \b \B \d \D \w [...] [^...] Fig. 35.13 Matches Beginning of string. 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 occurrence of the preceding pattern. Between m and n occurrences of the preceding pattern. Word boundary (i.e., the beginning or end of a word). Nonword boundary. Digit ([0–9]). Nondigit. Any alpha-numeric character. Any character defined by the set. Any character not defined by the set. re module’s regular-expression characters. 2004 Prentice Hall, Inc. All rights reserved. 35.5 Exception Handling • Enables programs and programmers to identify an error when it occurs and take appropriate action • try…except blocks 2004 Prentice Hall, Inc. All rights reserved. 35.5 Exception Handling 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 >>> Fig. 35.14 Interactive session illustrating a ZeroDivisionError exception. 2004 Prentice Hall, Inc. All rights reserved. 1 # Fig. 35.15: fig35_15.py 2 # A simple program that illustrates exceptions. Outline 3 4 5 def getFloat(): return float( raw_input( "Enter a number: " ) ) 6 7 fig35_15.py (1 of 1) number1 = number2 = None 8 9 10 while number1 == None: try: number1 = getFloat() 11 12 except ValueError: print "Value entered was not a number" 13 14 15 while number2 == None: 16 try: number2 = getFloat() 17 18 except ValueError: print "Value entered was not a number" 19 20 21 try: 22 result = number1 / number2 23 except ZeroDivisionError: 24 print "Cannot divide by zero!" 25 else: 26 print "The result of division is: %f" % result 2004 Prentice Hall, Inc. All rights reserved. 35.6 Introduction to CGI Programming • Use Python on the Web – cgi • For access to XHTML forms • Directive (pound-bang or Shebang) – Provides server with location of Python executable • cgi module – Provides functionalities for writing CGI scripts • environ data member – Holds all environment variables – Cookie • To read and write cookies – smtplib • To manipulate SMTP messages – urllib • To manipulate Web data – ftplib • To perform client-side FTP tasks 2004 Prentice Hall, Inc. All rights reserved. 1 #!c:\Python\python.exe 2 # Fig 35.16: fig35_16.py 3 # Program to display CGI environment variables Outline 4 5 import os 6 import cgi fig35_16.py (1 of 2) 7 8 print "Content-type: text/html" 9 print 10 11 print """<!DOCTYPE html PUBLIC 12 "-//W3C//DTD XHTML 1.0 Transitional//EN" 13 "DTD/xhtml1-transitional.dtd">""" 14 15 print """ 16 <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en" 17 lang="en"> 18 <head><title>Environment Variables</title></head> 19 <body><table style = "border: 0">""" 20 21 rowNumber = 0 22 23 for item in os.environ.keys(): 24 rowNumber += 1 25 2004 Prentice Hall, Inc. All rights reserved. 26 27 28 29 if rowNumber % 2 == 0: backgroundColor = "white" else: backgroundColor = "lightgrey" 30 31 print """<tr style = "background-color: %s"> 32 <td>%s</td><td>%s</td></tr>""" \ 33 % ( backgroundColor, item, 34 Outline fig35_16.py (2 of 2) cgi.escape( os.environ[ item ] ) ) 35 36 print """</table></body></html>""" 2004 Prentice Hall, Inc. All rights reserved. 35.7 Form Processing and Business Logic • XHTML forms – Allow users to enter data to be sent to a Web server for processing 2004 Prentice Hall, Inc. All rights reserved. 1 <!DOCTYPE html PUBLIC 2 "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "DTD/xhtml1-transitional.dtd"> 4 <!-- Fig. 35.17: fig35_17.html --> 5 6 7 8 9 Outline <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en" fig35_17.html (1 of 3) lang="en"> <head> <title>Sample FORM to take user input in HTML</title> 10 </head> 11 12 <body style = "font-family: Arial, sans-serif; font-size: 11pt"> 13 14 15 16 17 <div style = "font-size: 15pt; font-weight: bold"> This is a sample registration form. </div> Please fill in all fields and click Register. 18 19 <form method = "post" action = "/cgi-bin/fig35_18.py"> 20 <img src = "images/user.gif" alt = "user" /><br /> 21 <div style = "color: blue"> 22 23 Please fill out the fields below.<br /> </div> 24 25 <img src = "images/fname.gif" alt = "firstname" /> 2004 Prentice Hall, Inc. All rights reserved. 26 <input type = "text" name = "firstname" /><br /> 27 <img src = "images/lname.gif" alt = "lastname" /> 28 <input type = "text" name = "lastname" /><br /> 29 <img src = "images/email.gif" alt = "email" /> 30 <input type = "text" name = "email" /><br /> 31 <img src = "images/phone.gif" alt = "phone" /> 32 <input type = "text" name = "phone" /><br /> Outline fig35_17.html (2 of 3) 33 34 35 36 <div style = "font-size: 8pt"> Must be in the form (555)555-5555<br/><br/> </div> 37 38 <img src = "images/downloads.gif" alt = "downloads" /><br /> 39 <div style = "color: blue"> 40 41 Which book would you like information about?<br /> </div> 42 43 <select name = "book"> 44 <option>XML How to Program</option> 45 <option>Python How to Program</option> 46 <option>E-business and E-commerce How to Program</option> 47 <option>Internet and WWW How to Program 3e</option> 48 <option>C++ How to Program 4e</option> 49 <option>Java How to Program 5e</option> 50 <option>Visual Basic How to Program</option> 2004 Prentice Hall, Inc. All rights reserved. 51 </select> 52 <br /><br /> Outline 53 54 <img src = "images/os.gif" alt = "os" /><br /> 55 <div style = "color: blue"> 56 Which operating system are you 57 currently using?<br /> 58 fig35_17.html (3 of 3) </div> 59 60 <input type = "radio" name = "os" value = "Windows XP" 61 checked = "checked" /> 62 Windows XP 63 <input type = "radio" name = "os" value = "Windows 2000" /> 64 Windows 2000 65 <input type = "radio" name = "os" value = "Windows 95_98" /> 66 Windows 95/98/ME<br /> 67 <input type = "radio" name = "os" value = "Linux" /> 68 Linux 69 <input type = "radio" name = "os" value = "Other" /> 70 Other<br /> 71 <input type = "submit" value = "Register" /> 72 73 </form> 74 </body> 75 </html> 2004 Prentice Hall, Inc. All rights reserved. 2004 Prentice Hall, Inc. All rights reserved. 1 #!c:\Python\python.exe 2 # Fig. 35.18: fig35_18.py 3 # Program to read information sent to the server from the 4 # form in the form.html document. 5 6 import cgi 7 import re Outline fig35_18.py (1 of 4) 8 9 # the regular expression for matching most US phone numbers 10 telephoneExpression = \ 11 re.compile( r'^\(\d{3}\)\d{3}-\d{4}$' ) 12 13 def printContent(): 14 print "Content-type: text/html" 15 print 16 print """ 17 <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en" 18 lang="en"> 19 <head><title>Registration results</title></head> 20 <body>""" 21 22 def printReply(): 23 print """ 24 Hi <span style = "color: blue; font-weight: bold"> 25 %(firstName)s</span>. 2004 Prentice Hall, Inc. All rights reserved. 26 Thank you for completing the survey.<br /> 27 You have been added to the <span style = "color: blue; 28 font-weight: bold">%(book)s </span> mailing list.<br /><br /> Outline 29 30 <span style = "font-weight: bold"> 31 The following information has been saved in our database: 32 </span><br /> fig35_18.py (2 of 4) 33 34 35 <table style = "border: 0; border-width: 0; border-spacing: 10"> 36 <tr><td style = "background-color: yellow">Name </td> 37 <td style = "background-color: yellow">Email</td> 38 <td style = "background-color: yellow">Phone</td> 39 <td style = "background-color: yellow">OS</td></tr> 40 41 42 43 <tr><td>%(firstName)s %(lastName)s</td><td>%(email)s</td> <td>%(phone)s</td><td>%(os)s</td></tr> </table> 44 45 <br /><br /><br /> 46 47 <div style = "text-align: center; font-size: 8pt"> 48 This is only a sample form. 49 You have not been added to a mailing list. 50 </div></center> 2004 Prentice Hall, Inc. All rights reserved. 51 """ % personInfo Outline 52 53 def printPhoneError(): 54 55 print """<span style = "color: red; font-size 15pt"> 56 INVALID PHONE NUMBER</span><br /> 57 A valid phone number must be in the form 58 <span style = "font-weight: bold">(555)555-5555</span> 59 <span style = "color: blue"> Click the Back button, 60 enter a valid phone number and resubmit.</span><br /><br /> 61 Thank You.""" fig35_18.py (3 of 4) 62 63 def printFormError(): 64 65 print """<span style = "color: red; font-size 15pt"> 66 FORM ERROR</span><br /> 67 You have not filled in all fields. 68 <span style = "color: blue"> Click the Back button, 69 fill out the form and resubmit.</span><br /><br /> 70 Thank You.""" 71 72 printContent() 73 74 form = cgi.FieldStorage() 75 2004 Prentice Hall, Inc. All rights reserved. 76 try: 77 personInfo = { 'firstName' : form[ "firstname" ].value, 78 'lastName' : form[ "lastname" ].value, 79 'email' : form[ "email" ].value, 80 'phone' : form[ "phone" ].value, 81 'book' : form[ "book" ].value, 82 'os' : form[ "os" ].value } Outline fig35_18.py (4 of 4) 83 except KeyError: 84 printFormError() 85 86 if telephoneExpression.match( personInfo[ 'phone' ] ): 87 printReply() 88 else: 89 printPhoneError() 2004 Prentice Hall, Inc. All rights reserved. 35.8 Cookies • Small text files – State information • • • • Username Password Specific information helpful when user returns Etc. 2004 Prentice Hall, Inc. All rights reserved. 1 <!DOCTYPE html PUBLIC 2 "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "DTD/xhtml1-transitional.dtd"> 4 <!-- Fig. 35.19: fig35_19.html --> 5 6 <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang = "en" 7 lang = "en"> 8 <head> 9 10 Outline fig35_19.html (1 of 2) <title>Writing a cookie to the client computer</title> </head> 11 12 <body style = "background-image: images/back.gif; 13 font-family: Arial,sans-serif; font-size: 11pt" > 14 15 16 17 <span style = "font-size: 15pt; font-weight: bold"> Click Write Cookie to save your cookie data. </span><br /> 18 19 <form method = "post" action = "/cgi-bin/fig35_20.py"> 20 <span style = "font-weight: bold">Name:</span><br /> 21 <input type = "text" name = "name" /><br /> 22 <span style = "font-weight: bold">Height:</span><br /> 23 <input type = "text" name = "height" /><br /> 24 <span style = "font-weight: bold">Favorite Color</span><br /> 25 <input type = "text" name = "color" /><br /> 2004 Prentice Hall, Inc. All rights reserved. 26 27 <input type = "submit" value = "Write Cookie" /> </form> Outline 28 29 </body> 30 </html> fig35_19.html (2 of 2) 2004 Prentice Hall, Inc. All rights reserved. 1 #!C:\Python\python.exe 2 # Fig. 35.20: fig35_20.py 3 # Writing a cookie to a client's machine Outline 4 5 import cgi 6 import Cookie 7 import time fig35_20.py (1 of 3) 8 9 def printContent(): 10 print "Content-type: text/html" 11 print 12 print """ 13 <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en" 14 lang="en"> 15 <head><title>Cookie values</title></head>""" 16 17 form = cgi.FieldStorage() # get form information 18 19 try: # extract form values 20 name = form[ "name" ].value 21 height = form[ "height" ].value 22 color = form[ "color" ].value 23 except KeyError: 24 printContent() 25 print """<body><h3>You have not filled in all fields. 2004 Prentice Hall, Inc. All rights reserved. 26 <span style = "color: blue"> Click the Back button, 27 fill out the form and resubmit.<br /><br /> 28 Thank You. </span></h3>""" Outline 29 else: 30 31 # construct cookie expiration date and path 32 expirationFormat = "%A, %d-%b-%y %X %Z" 33 expirationTime = time.localtime( time.time() + 300 ) 34 expirationDate = time.strftime( expirationFormat, 35 36 fig35_20.py (2 of 3) expirationTime ) path = "/" 37 38 # construct cookie contents 39 cookie = Cookie.SimpleCookie() 40 41 cookie[ "Name" ] = name 42 cookie[ "Name" ][ "expires" ] = expirationDate 43 cookie[ "Name" ][ "path" ] = path 44 45 cookie[ "Height" ] = height 46 cookie[ "Height" ][ "expires" ] = expirationDate 47 cookie[ "Height" ][ "path" ] = path 48 49 cookie[ "Color" ] = color 50 cookie[ "Color" ][ "expires" ] = expirationDate 2004 Prentice Hall, Inc. All rights reserved. 51 cookie[ "Color" ][ "path" ] = path 52 53 # print cookie to user and page to browser 54 print cookie 55 56 printContent() 57 print """<body style = "background-image: /images/back.gif; 58 font-family: Arial,sans-serif; font-size: 11pt"> 59 The cookie has been set with the following data: <br /><br /> Outline fig35_20.py (3 of 3) 60 61 <span style = "color: blue">Name:</span> %s<br /> 62 <span style = "color: blue">Height:</span> %s<br /> 63 <span style = "color: blue">Favorite Color:</span> 64 <span style = "color: %s"> %s</span><br />""" \ 65 % ( name, height, color, color ) 66 67 print """<br /><a href= "fig35_21.py"> 68 Read cookie values</a>""" 69 70 print """</body></html>""" 2004 Prentice Hall, Inc. All rights reserved. 2004 Prentice Hall, Inc. All rights reserved. 1 #!C:\Python\python.exe 2 # Fig. 35.21: fig35_21.py 3 # Program that retrieves and displays client-side cookie values Outline 4 5 import Cookie 6 import os fig35_21.py (1 of 2) 7 8 print "Content-type: text/html" 9 print 10 print """ 11 <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en" 12 lang="en"> 13 <head><title>Cookie values</title></head> 14 <body style = 15 font-family: Arial, sans-serif; font-size: 11pt">""" 16 17 try: 18 cookie = Cookie.SimpleCookie() 19 cookie.load( os.environ[ "HTTP_COOKIE" ] ) 20 except KeyError: 21 print """<span style = "font-weight: bold">Error reading cookies 22 </span>""" 23 else: 24 print """<span style = "font-weight: bold"> 25 The following data is saved in a cookie on your computer. 2004 Prentice Hall, Inc. All rights reserved. 26 </span><br /><br />""" 27 28 29 print """<table style = "border-width: 5; border-spacing: 0; padding: 10">""" 30 31 32 for item in cookie.keys(): fig35_21.py (2 of 2) print """<tr> 33 <td style = "background-color: lavender">%s</td> 34 <td style = "background-color: white">%s</td> 35 Outline </tr>""" % ( item, cookie[ item ].value ) 36 37 print """</table>""" 38 39 print """</body></html>""" 2004 Prentice Hall, Inc. All rights reserved. 35.9 Database Application Programming Interface (DB-API) • Python Database Special Interest Group (SIG) – Formed to develop a specification for Python database application programming interface (DB-API) 2004 Prentice Hall, Inc. All rights reserved. 35.9.1 Setup • MySQL and the MySQLdb module must be installed 2004 Prentice Hall, Inc. All rights reserved. 35.9.2 Simple DB-API Program • Lets user choose an author from XHTML dropdown list • User clicks button to query database • Database query returns a list of all books by author 2004 Prentice Hall, Inc. All rights reserved. 1 #!c:\Python\python.exe 2 # Fig. 35.22: fig35_22.py 3 # A program to illustrate Python's database connectivity. 4 import MySQLdb Outline fig35_22.py (1 of 2) 5 6 print "Content-type: text/html" 7 print 8 print """ 9 <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en" 10 lang="en"> 11 <head><title>Select Author</title></head> 12 <body style = 13 font-family: Arial, sans-serif; font-size: 11pt">""" 14 15 try: 16 connection = MySQLdb.connect( db = "books" ) 17 except OperationalError: 18 print "Unable to connect to database: %s" % message 19 else: 20 cursor = connection.cursor() 21 cursor.execute( "SELECT * FROM Authors" ) 22 authorList = cursor.fetchall() 23 24 cursor.close() # close cursor 25 connection.close() # close connection 2004 Prentice Hall, Inc. All rights reserved. 26 27 print """ 28 <form method = "post" action = "/cgi-bin/fig35_23.py"> 29 <select name = "authorID">""" fig35_22.py (2 of 2) 30 31 32 33 Outline for author in authorList: print """<option value = %d>%s, %s</option>""" \ % ( author[ 0 ], author[ 2 ], author[ 1 ] ) 34 35 print """ 36 </select> 37 <input type = "submit" value = "Execute Query" /> 38 </ form>""" 39 40 print """</body></html>""" 2004 Prentice Hall, Inc. All rights reserved. 1 #!c:\Python\python.exe 2 # Fig. 35.23: fig35_23.py 3 # A program to illustrate Python's database connectivity. Outline 4 5 import cgi 6 import MySQLdb 7 import sys fig35_23.py 1 of 3 8 9 # get results from form 10 form = cgi.FieldStorage() 11 12 print "Content-type: text/html" 13 print 14 print """ 15 <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en" 16 lang="en"> 17 <head><title>Query results</title></head> 18 <body style = 19 font-family: Arial, sans-serif; font-size: 11pt">""" 20 21 try: 22 authorID = form[ "authorID" ].value 23 except KeyError: 24 print """<span style = "color: red size = 15pt"> 25 FORM ERROR</span><br /> 2004 Prentice Hall, Inc. All rights reserved. 26 You did not select an author.<br /> 27 <span style = "color: blue"> Click the Back button, 28 fill out the form and resubmit.<br /><br /> 29 Thank You.</span></body></html>""" 30 sys.exit() Outline fig35_23.py (2 of 3) 31 32 # connect to database and get cursor 33 try: 34 connection = MySQLdb.connect( db = 'books' ) 35 except OperationalError: 36 print """<span style = "color: red size = 15pt"> 37 DATABASE ERROR</span><br /> Unable to connect to database. 38 </body></html>""" 39 sys.exit() 40 41 queryString = """select Titles.* from Titles, AuthorISBN 42 where AuthorISBN.AuthorID=%s and 43 Titles.ISBN=AuthorISBN.ISBN""" % authorID 44 45 cursor = connection.cursor() 46 cursor.execute( queryString ) 47 48 results = cursor.fetchall() 49 50 cursor.close() # close cursor 2004 Prentice Hall, Inc. All rights reserved. 51 connection.close() # close connection 52 53 # display results Outline 54 print """<table style = "border: groove 2 pt; 55 56 border-colapse: separate"> <tr> 57 <th>ISBN</th> 58 <th>Title</th> 59 <th>Edition</th> 60 <th>Year</th> 61 <th>Description</th> 62 <th>Publisher ID</th> 63 fig35_23.py (3 of 3) </tr>""" 64 65 for row in results: 66 print "<tr>" 67 68 69 for entry in row: print '<td style = "border: solid 2pt">%s</td>' % entry 70 71 print "</tr>" 72 73 print """</table></body></html>""" 2004 Prentice Hall, Inc. All rights reserved. 2004 Prentice Hall, Inc. All rights reserved. 35.10 Operator Precedence Chart Operator Type Associativity ' ' string conversion left to right { } [ ] ( ) ( ) [ : ] [ ] . ** ~ + * / % Fig. 35.24 dictionary creation list creation tuple creation or expression grouping function call slicing subscript access member access exponentiation bitwise NOT unary plus unary minus multiplication division modulus (remainder) Python operator precedence chart. 2004 Prentice Hall, Inc. All rights reserved. left to right left to right left to right left to right left to right left to right left to right right to left left to right right to left left to right 35.10 Operator Precedence Chart Operator + << >> & ^ | < <= > >= != == Fig. 35.24 Type addition subtraction left shift right shift bitwise AND bitwise XOR bitwise OR less than less than or equal greater than greater than or equal not equal equal Python operator precedence chart. 2004 Prentice Hall, Inc. All rights reserved. Associativity left to right left to right left to right left to right left to right left to right 35.10 Operator Precedence Chart Operator Type Associativity is, is not identity left to right in, not in not and or lambda Fig. 35.24 membership tests boolean NOT boolean AND boolean OR lambda expressions (anonymous functions) Python operator precedence chart. 2004 Prentice Hall, Inc. All rights reserved. left to right left to right left to right left to right left to right 35.11 Web Resources • • • • • • • • • • • • • • • • • • • www.python.org www.zope.com www.zope.org starship.python.net www.python.org/download/download_mac.html www.vex.net/parnassus www.pythonware.com starship.python.net/crew/davem/cgifaq/faqw.cgi www.devshed.com/Server_Side/Python/CGI starship.python.net/crew/aaron_watters/pws.html www.python.org/doc/howto/regex/regex.html www.python.org/windows/win32com gadfly.sourceforge.net aspn.activestate.com/ASPN/Python/Cookbook www.python.org/windows/win32/odbc.html starship.python.net/crew/bwilk/access.html www.python.org/doc/Comparisons.html www.vic.auug.org.au/auugvic/av_paper_python.html www.networkcomputing.com/unixworld/tutorial/005/005.html 2004 Prentice Hall, Inc. All rights reserved.