Perl_27_Python by luckbbs

VIEWS: 2 PAGES: 80

									          Chapter 27 – Bonus: Introduction to
                Python Programming
        Outline
        27.1           Introduction
                       27.1.1 A First Python Program
                       27.1.2 Python Keywords
        27.2           Basic Data Types, Control Structures and Functions
        27.3           Tuples, Lists and Dictionaries
        27.4           String Processing and Regular Expressions
        27.5           Exception Handling
        27.6           Introduction to CGI Programming
        27.7           Form Processing and Business Logic
        27.8           Cookies
        27.9           Database Application Programming Interface (DB-API)
                       27.9.1 Setup
                       27.9.2 A Simple DB-API Program




 2001 Prentice Hall, Inc. All rights reserved.
          Chapter 27 – Bonus: Introduction to
                Python Programming
        Outline
        27.10          Object-Oriented Programming
        27.11          Cast Study: GUI Database Application
                       27.11.1 Gadfly
                       27.11.2 Tkinter
                       27.11.3 Setup
                       27.11.4 GUI Database Viewer Implementation
        27.12          Operator Precedence Chart
        27.13          Internet and World Wide Web Resources




 2001 Prentice Hall, Inc. All rights reserved.
                                            27.1 Introduction

      • Python
              – Interpreted, cross-platform, object-oriented language
              – Open source
                     • Encouraged a wide variety of programmers to develop and
                       submit modules
      • Comparison
              – Perl is better for system administrative programming tasks
              – Python is structured and object-oriented




 2001 Prentice Hall, Inc. All rights reserved.
                          27.1.1 A First Python Program

      • Python
              – Executed through a program in a file
              – Run through interactive mode
                     • Used to test small blocks of code quickly
              – To run a program
                     • Type python fileName.py
                     • Type just python to enter interactive mode




 2001 Prentice Hall, Inc. All rights reserved.
1       # Fig. 27.1: fig27_01.py                                                 Outline
2       # A first program in Python
3                                                     Prints out the text
4       print "Welcome to Python!"                    “Welcome to Python”
                                                                            fig27_01.py

Welcome to Python!




     2001 Prentice Hall, Inc. All rights reserved.
                          27.1.1 A First Python Program




              Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
              Type "copyright", "credits" or "license" for more information.
              >>> print "Welcome to Python!"
              Welcome to Python!
              >>> ^Z




        Fig. 27.2 Python in interactive mode.


 2001 Prentice Hall, Inc. All rights reserved.
                                  27.1.2 Python Keywords

      • Keywords
              – A list can be found in Fig 27.3
              – The keyword module can also be used to obtain keywords




 2001 Prentice Hall, Inc. All rights reserved.
                                  27.1.2 Python Keywords




      Python keyw ord s
      and        continue else                    for      import   not     raise
      assert        def        except             from     in       or      return
      break         del        exec               global   is       pass    try
      class         elif       finally            if       lambda   print   while
      Fig. 27.3 Python keyw ord s.




 2001 Prentice Hall, Inc. All rights reserved.
         27.2 Basic Data Types, Control Structures
                       and Function
      • Functions
              – The def keyword is used to mark the beginning of a
                function
              – Parameters are set in parenthesis ()
              – The parameter list is followed by a colon (:)
              – Python determines a new line based on white spaces
                     • Indented blocks must be of the same indention




 2001 Prentice Hall, Inc. All rights reserved.
         27.2 Basic Data Types, Control Structures
                       and Function



             Python 2.0 (#8, Oct 16 2000, 17:27:58) [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. 27.4 Printing Python keywords in interactive mode.


 2001 Prentice Hall, Inc. All rights reserved.
1        # Fig. 27.5: fig27_05.py                                                                    Outline
2        # Program to illustrate basic data types, control structures and
3        # functions.
4
5        def greatestCommonDivisor( x, y ):                                                   fig27_05.py
6           gcd = min( x, y )
7
8            while gcd >= 1:
9
10                if ( x % gcd ) == ( y % gcd ) == 0:
11                   return gcd
                                                                    Returns the GCD of
12                else:                                             the two numbers
13                   gcd -= 1
14
15       def determineIfPythonPerl( name ):
16                                                                Determines if the passed
17           if name == "Python":
18              print "You entered Python!"            variable          is either Perl or Python
19           elif name == "Perl":
20              print "You entered Perl!"
21           else:
22              print "You did not enter Python or Perl."
23                                     White spaces are used to determine
24       number1 = int( raw_input( a function positiveends
                             where "Enter a or a line integer: " ) )                       Prompts the user
25       number2 = int( raw_input( "Enter a positive integer: " ) )                        for two numbers
26
27       print "The greatest common divisor is", \
28          greatestCommonDivisor( number1, number2 )                               Passes the two numbers
29                                                                                  to the functions
                                                                                            Loops through 5 times
30       for entry in range( 5 ):
31          language = raw_input( "\nEnter a programming language: " )                     prompting the user for a
32          determineIfPythonPerl( language )                                              programming language
                                                                                           and passing that on to
                                                                                           the function called
      2001 Prentice Hall, Inc. All rights reserved.
Enter a positive integer: 30                             Outline
Enter a positive integer: 2
The greatest common divisor is 2
Enter a programming language: Tcl
You did not enter Python or Perl.                   fig27_05.py

Enter a programming language: Java
You did not enter Python or Perl.

Enter a programming language: C++
You did not enter Python or Perl.

Enter a programming language: Python
You entered Python!

Enter a programming language: Perl
You entered Perl!




   2001 Prentice Hall, Inc. All rights reserved.
         27.2 Basic Data Types, Control Structures
                       and Function

        Esc a p e se q ue nc e                    Mea ning
        \n                                        Newline (line feed).
       \r                          Carriage return.
       \f                          Form feed.
       \t                          Tab.
       \v                          Vertical tab.
       \'                          Single quote.
       \"                          Double quote.
       \b                          Backspace.
       \\                          Backslash.
       Fig. 27.6 Esc a p e se q ue nc e s.




 2001 Prentice Hall, Inc. All rights reserved.
                   27.3 Tuples, Lists, and Dictionaries

      • List
              – Sequence of related data
      • Tuple
              – A constant list
      • Dictionary
              – List of values accessed through associated keys




 2001 Prentice Hall, Inc. All rights reserved.
1        # Fig. 27.7: fig27_07.py                                                                         Outline
2        # A program that illustrates tuples, lists and dictionaries.
3
4        # tuples                                      Creates a tuple with 3 values
5        aTuple = ( 1, 2, 3 )                          #   create tuple                                fig27_07.py
6        firstItem = aTuple[ 0 ]                       #   first tuple item
                                                                               Sets the values equal to
7        secondItem = aTuple[ 1 ]                      #   second tuple item   the values in the tuple
8        thirdItem = aTuple[ 2 ]                       #   third tuple item
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      Is the             same as lines 6-8
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
                                           Adds an elements
19       print
20                                         onto the tuple
21       aTuple += ( 4, )     # add an item to the end of the tuple
22       print "Added an item to the tuple using the += operator"
23       print
24
25       # print each item in tuple
26       print "The raw tuple data is:", aTuple                      Prints the whole tuple
27       print "The items in the tuple are:"
28
29       for item in aTuple:                     Prints out each
30           print item,                         item in the tuple
31
32       print            # end previous line
33       print            # blank line
34

      2001 Prentice Hall, Inc. All rights reserved.
35       # lists                                                                                        Outline
36       aList = [ 1, 2, 3 ]                 # create list
37       aList[ 0 ] = 0
                                                   Creates a list with 3
                                             # change first element of list
38       aList.append( 5 )                          item sets the first to
                                             # add items, to end of list0
39                                                                                            fig27_07.py
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 += operator"
45       print
46
47       # print each item in the list
48       print "The items in the list are:"
49
50       for item in aList:
51           print item,
52                                                          Creates a dictionary with the
53       print            # end previous line               given key element pairs
54       print            # blank line
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
65       print "The entries in the dictionary are:"    Uses             the dictionaries keys to
66                                                                 access the items in the dictionary
67       for item in aDictionary.keys():
68           print "aDictionary[ ", item, " ] = ", aDictionary[ item ]

      2001 Prentice Hall, Inc. All rights reserved.
The first item in the tuple is 1                                               Outline
The second item in the tuple is 2
The third item in the tuple is 3

The first item in the tuple is 1
                                                                          fig27_07.py
The second item in the tuple is 2
The third item in the tuple is 3

Added an item to the tuple using the += operator

The raw tuple data is: (1, 2, 3, 4)
The items in the tuple are:
1 2 3 4

The raw list data is: [0, 2, 3, 5]

Added an item to the list using the += operator

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.
The entries in the dictionary are:                       Outline
aDictionary[ 12 ] = December
aDictionary[ 11 ] = November
aDictionary[ 10 ] = October
aDictionary[ 9 ] = September
                                                    fig27_07.py
aDictionary[ 8 ] = August
aDictionary[ 7 ] = July
aDictionary[ 6 ] = June
aDictionary[ 5 ] = May
aDictionary[ 4 ] = April
aDictionary[ 3 ] = March
aDictionary[ 2 ] = February
aDictionary[ 1 ] = January




   2001 Prentice Hall, Inc. All rights reserved.
                   27.3 Tuples, Lists, and Dictionaries

      Method                            Purp ose
      append( item )                    Inserts item at the end of the list.
      count( element )      Returns the number of occurrences of element in the list.
      extend( newList )     Inserts newList at the end of the list.
      index( element )      Returns the index of the first occurrence of element in the list. If
                            element is not in the list, a ValueError exception occurs. [Note: We
                            discuss exceptions in Section 26.5]
      insert( index, item ) Inserts item at position index.
      pop( [index] )           Removes and returns the last element in the list. If parameter index is
                               specified, removes and returns the element at position index.
      remove( element )        Removes the first occurrence of element from the list. If element is not
                               in the list, a ValueError exception occurs.
      reverse()                Reverses the items in the list.
      sort( [function] )       Sorts items of the list. Optional parameter function is a comparison
                               function that may be user-defined.
      Fig. 27.8 Python list method s.



 2001 Prentice Hall, Inc. All rights reserved.
                   27.3 Tuples, Lists, and Dictionaries

      Method                          Desc rip tion
      clear()                         Deletes all items from the dictionary.
      copy()                  Creates a copy of the dictionary.
      get( key [, falseValue] Returns the value associated with key. If key is not in the dictionary and if
      )                       falseValue is specified, returns the specified value.
      has_key( key )                  Returns 1 if key is in the dictionary; returns 0 if key is not in the
                                      dictionary.
      items()                         Returns a list of tuples that are key-value pairs.
      keys()                          Returns a list of keys in the dictionary.
      setdefault( key [,              Behaves similarly to method get. If key is not in the dictionary and
      falseValue] )                   falseValue is specified, inserts the key and the specified value into
                                      dictionary.
     update(                          Adds all key-value pairs from newDictionary to the current dictionary.
     newDictionary )
     values()                 Returns a list of values in the dictionary.
     Fig. 27.9 Dic tiona ry method s.



 2001 Prentice Hall, Inc. All rights reserved.
                   27.4 String Processing and Regular
                              Expressions
      • Regular expressions
              – Patterns of characters used to search though text
              – Use the re module to perform such as task




 2001 Prentice Hall, Inc. All rights reserved.
1        # Fig. 27.10: fig27_10.py                                                                Outline
2        # Program to illustrate use of strings
3
4        # simple string assignments
5        string1 = "This is a string."                                                    fig27_10.py
6        print string1
                                                       Creates two strings
7
8        string2 = "This is a second string."
9        print string2
10
11       # string concatenation
12       string3 = string1 + " " + string2
13       print string3                                     Adds the two strings
14
15       # using operators
16       string4 = '*'
17       print "String with an asterisk: " + string4
18       string4 *= 50                                                Multiplies string4 to
19       print "String with 50 asterisks: " + string4                 duplicate the contents 50 times
20
21       # using quotes
22       print "This is a string with \"double quotes.\""            Strings can be character
                                                                    Uses an escape composed
23       print 'This is another string with "double quotes."'
24       print 'This is a string with \'single quotes.\''
                                                                     in single or double quotes
25       print "This is another string with 'single quotes.'"
26       print """This string has "double quotes" and 'single quotes.'"""
27
28       # string formatting
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 )




      2001 Prentice Hall, Inc. All rights reserved.
This is a string.                                           Outline
This is a second string.
This is a string. This is a second string.
String with an asterisk: *
String with 50 asterisks:                              fig27_10.py
**************************************************
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.




   2001 Prentice Hall, Inc. All rights reserved.
                   27.4 String Processing and Regular
                              Expressions
        Sym b ol                       Mea ning
        c                              Single character (i.e., a string of length one).
        s                           String.
        d                           Signed decimal integer.
        u                           Unsigned decimal integer.
        o                           Unsigned octal integer.
        x                           Unsigned hexadecimal integer (using format abcdef).
        X                           Unsigned hexadecimal integer (using format ABCDEF).
        f                           Floating-point number.
        e, E                        Floating-point number (using scientific notation).
        g, G                        Floating-point number (using least-significant digits).
        Fig. 27.11            String -form a t c ha ra c ters.




 2001 Prentice Hall, Inc. All rights reserved.
1    # Fig. 27.12: fig27_12.py                                                     Outline
2    # Program searches a string using the regular expression module.
3
4    import re              Uses the re module                                fig27_12.py
5
6    searchString = "Testing pattern matches"
7
8    expression1   =   re.compile(   r"Test" )        Searches the string
9    expression2   =   re.compile(   r"^Test" )       for the specific text
10   expression3   =   re.compile(   r"Test$" )
11   expression4   =   re.compile(   r"\b\w*es\b" )
12
13   if expression1.match( searchString ):
14      print '"Test" was found.'
15
16   if expression2.match( searchString ):
17      print '"Test" was found at the beginning of the line.'
18
19   if expression3.match( searchString ):
20      print '"Test" was found at the end of the line.'
21
22   result = re.findall( expression4, searchString )
23
24   if result:
25      print 'There are %d words(s) ending in "es":' % \
26      ( len( result ) ),
27
28      for item in result:
29         print " " + item,
30
31   print

"Test" was found.
"Test" was found at the beginning of the line.
There are 1 words(s) ending in "es": matches
   2001 Prentice Hall, Inc. All rights reserved.
                   27.4 String Processing and Regular
                              Expressions
         Cha ra c te r                 Ma tc he s
         ^                             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 occurrences of the preceding pattern.
        {m, n}                      Between m and n occurrences of the preceding pattern.
        \b                          Word boundary (i.e., the beginning or end of a word).
        \B                          Non-word boundary.
        \d                          Digit ([0–9]).
        \D                          Non-digit.
        \w                          Any alpha-numeric character.
        [...]                       Any character defined by the set.
        [^...]                      Any character not defined by the set.
        Fig. 27.13            So m e o f re m o d ule’ s reg ula r e xp ressio n c ha ra c te rs.




 2001 Prentice Hall, Inc. All rights reserved.
                                  27.5 Exception Handling

      • Errors
              – Most errors caught at compilation-time cannot be caught
                until run-time when using the interactive mode
              – Occur when a block of code reaches an error that it is unable
                to handle, thus it raises an exception
              – Use try/except blocks
                     • Can catch one, all, or a sub-set of exceptions




 2001 Prentice Hall, Inc. All rights reserved.
                                  27.5 Exception Handling



          Python 2.0 (#8, Oct 16 2000, 17:27:58) [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
          >>>




        Fig. 27.14 Interactive session illustrating a ZeroDivisionError exception.


 2001 Prentice Hall, Inc. All rights reserved.
1        # Fig. 27.15: fig27_15.py                                                                Outline
2        # A simple program that illustrates exceptions.
3
4        def getNumber():
5                                                      Gets a number from the user      fig27_15.py
6            while 1:   # creates infinite loop
7               try:
8                  theNumber = float( raw_input( "Enter a number: " ) )
9                  return theNumber
10              except ValueError:
11                 print "Value entered was not a number."            Makes         sure that the entered
12                                                                           value was a number
13       def divideNumbersString( x, y ):
14          try:
15             result = x / y
16          except ZeroDivisionError:                 Checks for       the divide by zero error
17             return "Cannot divide by zero!"
18          else:
19             return "The result of division is: %f" % result
20
21       number1 = getNumber()
22       number2 = getNumber()
23
24       print divideNumbersString( number1, number2 )


Enter a number: 4
Enter a number: 2
The result of division is: 2.000000




      2001 Prentice Hall, Inc. All rights reserved.
Enter a number: 4                                        Outline
Enter a number: 0
Cannot divide by zero!
                                                    fig27_15.py
Enter a number: a
Value entered was not a number.
Enter a number: 1
Enter a number: 9
The result of division is: 0.111111




   2001 Prentice Hall, Inc. All rights reserved.
               27.6 Introduction to CGI Programming

      • Python has many Web uses
              – cgi module
                     • Used to help generate HTML forms
              – Cookie module
                     • Used to read and write cookies
              – smtplib module
                     • Used to work with STMP messages
              – urllib module
                     • Used to work with web data
              – ftplib module
                     • Used to perform client-side ftp tasks
              – HTMLgen module
                     • Used to generate HTML pages

 2001 Prentice Hall, Inc. All rights reserved.
1        #!c:\Python\python.exe                                                                   Outline
2        # Fig. 27.16: fig27_16.py
3        # Program to display CGI environment variables
4
5        import os                                                                        fig27_16.py
6
7        print "Content-type: text/html"
8        print
9
10       print """<html><head><title>Environment Variables</title>                 Sets the title of
11       </head><table border = "0" celmargin = "5">"""                            the Web page
12
13       rowNumber = 0
14       backgroundColor = "#FFFFFF"
15
16       for item in os.environ.keys():
17          rowNumber += 1
18
                                                       Alternates the row color
19           if rowNumber % 2 == 0:
20              backgroundColor = "#FFFFFF"
21           else:                                          Prints the cell of the form
22              backgroundColor = "#DDDDDD"
23
24           print """<tr bgcolor = %s><td>%s</td><td>%s</td></tr>""" \
25              % ( backgroundColor, item, os.environ[ item ] )
26
27       print """</table></body></html>"""




      2001 Prentice Hall, Inc. All rights reserved.
                                                                                                       Outline

                                                                                                  fig27_16.py




         Netscape Communicator browser window ©1999 Netscape Communications Corporation.
         Used with permission. Netscape Communications has not authorized, sponsored, endorsed,
         or approved this publication and is not responsible for its content.




 2001 Prentice Hall, Inc. All rights reserved.
          27.7 Form Processing and Business Logic

      • HTML forms
              – Allow data to be sent to a Web server




 2001 Prentice Hall, Inc. All rights reserved.
1        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">                      Outline
2        <!-- Fig. 27.17: fig27_17.html -->
3
4        <html>
5        <head>                                                                     fig27_17.py
6        <title>Sample FORM to take user input in HTML</title>
7        </head>
8
9        <body background = "images/back.gif">
10       <basefont face = "arial,sans-serif" size = "2">
11                                                                     Specifies how the
12           <font size = "+2">                                        information enclosed in the
13              <strong>This is a sample registation form.</strong>
14           </font><br>                                               form tags should be handled
15           Please fill in all fields and click Register.
16
17           <form method = "post" action = "/cgi-bin/fig27_18.py">
18              <img src = "images/user.gif"><br>
19              <font color = "blue">
20                 Please fill out the fields below.<br>
21              </font>
22
23                <img src = "images/fname.gif">                 Several fields to be filled out
24                <input type = "text" name = "firstname"><br>
25                <img src = "images/lname.gif">
26                <input type = "text" name = "lastname"><br>
27                <img src = "images/email.gif">
28                <input type = "text" name = "email"><br>
29                <img src = "images/phone.gif">
30                <input type = "text" name = "phone"><br>
31
32                <font size = "-2">
33                   Must be in the form (555)555-5555<br><br>
34                </font>
35
      2001 Prentice Hall, Inc. All rights reserved.
36                <img src = "images/downloads.gif"><br>                                           Outline
37                <font color = "blue">
38                   Which book would you like information about?<br>
39                </font>
40                                                                                            fig27_17.py
41                <select name = "book">                      A drop down          list
42                   <option>Perl How to Program
43                   <option>Python How to Program
44                   <option>E-business and E-commerce How to Program
45                   <option>Internet and WWW How to Program
46                   <option>C++ How to Program 3e
47                   <option>Java How to Program 3e
48                   <option>Visual Basic How to Program
49                </select>
50                <br><br>
51
52                <img src = "images/os.gif"><br>
53                <font color = "blue">
54                   Which operating system are you
55                   currently using?<br>                    Radio buttons to choose the OS
56                </font>
57
58                <input type = "radio" name =         "os" value = "Windows NT"
59                checked>
60                Windows NT
61                <input type = "radio" name =         "os" value = "Windows 2000">
62                Windows 2000
63                <input type = "radio" name =         "os" value = "Windows 95_98">
64                Windows 95/98<br>
65                <input type = "radio" name =         "os" value = "Linux">
66                Linux
67                <input type = "radio" name =         "os" value = "Other">
68                Other<br>
69                <input type = "submit" value         = "Register">

      2001 Prentice Hall, Inc. All rights reserved.
70
71          </form>                                                                                               Outline
72       </body>
73       </html>
                                                                                                             fig27_17.py




 Netscape Communicator browser window ©1999 Netscape Communications Corporation. Used with
 permission. Netscape Communications has not authorized, sponsored, endorsed, or approved this publication
 and is not responsible for its content.

      2001 Prentice Hall, Inc. All rights reserved.
1        #!c:\Python\python.exe                                                                      Outline
2        # Fig. 27.18: fig27_18.py
3        # Program to read information sent to the server from the
4        # form in fig27_17.html.
5                                                                                           fig27_18.py
6        import cgi                 Imports the cgi module
7        import re
8
9        # the regular expression for matching most American phone numbers.
10       telephoneExpression = \
11          re.compile( r'\(\d\d\d\)\d\d\d-\d\d\d\d' )
12
13       def printContent():
14          print "Content-type: text/html"
15          print
16
17       def printReply():
18          print """Hi <font color = "blue"><b>%(firstName)s</b></font>.
19             Thank you for completing the survey.<BR>
20             You have been added to the
21             <font color = "blue"><strong>%(book)s </strong></font>
22             mailing list.<br><br>
23
24                <strong>The following information has been saved
25                in our database:</strong><br>
26
27                <table border = "0" cellpadding = "0"                Generates a table the displays
28                    cellspacing = "10">
29
                                                                       the data the user entered after it
30                <tr><td     bgcolor     =   "#FFFFAA">Name </td>     was entered into the database
31                    <td     bgcolor     =   "#FFFFAA">Email</td>
32                    <td     bgcolor     =   "#FFFFAA">Phone</td>
33                    <td     bgcolor     =   "#FFFFAA">OS</td></tr>
34

      2001 Prentice Hall, Inc. All rights reserved.
35                <tr><td>%(firstName)s %(lastName)s</td><td>%(email)s</td>                          Outline
36                    <td>%(phone)s</td><td>%(os)s</td></tr>
37                </table>
38
39                <br><br><br>                                                                  fig27_18.py
40
41                <center><font size = "-3">
42                This is only a sample form.
43                You have not been added to a mailing list.
44                </font></center>
45                """ % personInfo
                                                             The           function called if the
46                                                                    user did not enter the
47       def printPhoneError():                                       correct telephone format
48
49           print """<font color = "red" size = "+2">
50              INVALID PHONE NUMBER</font><br>
51              A valid phone number must be in the form
52              <strong>(555)555-5555</strong>
53              <font color = "blue"> Click the Back button,
54              enter a valid phone number and resubmit.<br><br>
55              Thank You."""                 The function called if           all the user
56
57       def printFormError():                         data fields were not filled out
58
59           print """<font color = "red" size = "+2">
60              FORM ERROR</font><br>
61              You have not filled in all fields.
62
63                <font color = "blue"> Click the Back button,
64                fill out the form and resubmit.<br><br>
65                Thank You.</font>"""
66
67       printContent()
68
69       form = cgi.FieldStorage()
      2001 Prentice Hall, Inc. All rights reserved.
70                                                                                                       Outline
71       try:
72          personInfo = { 'firstName' : form[ "firstname" ].value,
73                         'lastName' : form[ "lastname" ].value,
74                         'email' : form[ "email" ].value,                                      fig27_18.py
75                         'phone' : form[ "phone" ].value,
76                         'book' : form[ "book" ].value,
77                         'os' : form[ "os" ].value }
78       except:
79          printFormError()
80                                                               Compared the user entered values to the
81       if telephoneExpression.match( personInfo[               'phone' ] ):
                                                                 appropriate form that is in the dictionary
82          printReply()
83       else:
84          printPhoneError()
85          printPhoneError()

                                             Makes sure that the phone
                                             number is of the right format




      2001 Prentice Hall, Inc. All rights reserved.
                                                                                                                 Outline

                                                                                                            fig27_18.py




Netscape Communicator browser window ©1999 Netscape Communications Corporation. Used with
permission. Netscape Communications has not authorized, sponsored, endorsed, or approved this publication
and is not responsible for its content.



 2001 Prentice Hall, Inc. All rights reserved.
                                                                                                                 Outline

                                                                                                            fig27_18.py




Netscape Communicator browser window ©1999 Netscape Communications Corporation. Used with
permission. Netscape Communications has not authorized, sponsored, endorsed, or approved this publication
and is not responsible for its content.




 2001 Prentice Hall, Inc. All rights reserved.
                                                  27.8 Cookies

      • Cookies
              – Can be written to a client machine
              – Usually small text files used to maintain state information
                     • Username and or password as well as useful information for
                       when the user returns to the site




 2001 Prentice Hall, Inc. All rights reserved.
1        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">                     Outline
2        <!-- Fig. 27.19: fig27_19.html -->
3
4        <html>
5           <head>                                                                  fig27_19.py
6               <title>Writing a cookie to the client computer</title>
7           </head>
8
9        <body background = "images/back.gif">
10       <basefont face = "arial,sans-serif" size = "2">
11
12           <font size = "+2">
13              <b>Click Write Cookie to save your cookie data.</b>
14           </font><br>
15
16           <form method = "post" action = "cgi-bin/fig27_20.py">
17              <strong>Name:</strong><br>
18              <input type = "text" name = "name"><br>
                                                                            Creates a form that asks
19
20                <strong>Height:</strong><br>                              for the users name,
21                <input type = "text" name = "height"><br>                 height, and favorite color
22
23                <strong>Favorite Color</strong><br>
24                <input type = "text" name = "color"><br>
25
26              <input type = "submit" value = "Write Cookie">
                                                                      By clicking the button a cookie
27           </form>                                                  can be saved storing the data
28
29       </body>
30       </html>




      2001 Prentice Hall, Inc. All rights reserved.
                                                       Outline

                                                  fig27_19.py




 2001 Prentice Hall, Inc. All rights reserved.
1        #!C:\Python\python.exe                                                           Outline
2        # Fig. 27.20: fig27_20.py
3        # Writing a cookie to a client's machine
4
5        import cgi                                                                fig27_20.py
6        import Cookie
7        import time
8
9        form = cgi.FieldStorage()                # get form information
10
11       try: # extract form values
12          name = form[ "name" ].value
13          height = form[ "height" ].value         Get the user entered values
14          color = form[ "color" ].value
15       except:
16          print "Content-type: text/html"
17          print
18          print """<h3>You have not filled in all fields.
                                                                     An exception for when the user
19          <font color = "blue"> Click the Back button,
20          fill out the form and resubmit.<br><br>                  does not fill everything out
21          Thank You. </font></h3>"""
22       else:
23          # construct cookie expiration date and path
24          expirationFormat = "%A, %d-%b-%y %X %Z"                       Creates the expiration
25          expirationTime = time.localtime( time.time() + 300 )
26          expirationDate = time.strftime( expirationFormat,             date of the cookie
27             expirationTime )
28          path = "/"
29
30           # construct cookie contents
31           cookie = Cookie.Cookie()                         Creates the cookie
32



      2001 Prentice Hall, Inc. All rights reserved.
33           cookie[ "Name" ] = name                                                                 Outline
34           cookie[ "Name" ][ "expires" ] = expirationDate
35           cookie[ "Name" ][ "path" ] = path
                                                                          Creates the cookies with
36
37           cookie[ "Height" ] = height                                                     fig27_20.py
                                                                          the name, height, and color
38           cookie[ "Height" ][ "expires" ] = expirationDate
39           cookie[ "Height" ][ "path" ] = path
40
41           cookie[ "Color" ] = color
42           cookie[ "Color" ][ "expires" ] = expirationDate
43           cookie[ "Color" ][ "path" ] = path
44
45           # print cookie to user and page to browser
46           print cookie
47
48           print "Content-type: text/html"
49           print
50
51           print """<body background = "/images/back.gif">
52           <basefont face = "arial,sans-serif" size = "3">
53           The cookie has been set with the folowing data: <br><br>
54
55           <font     color    =   "blue">Name:</font> %s<br>              Displays the contents    of
56           <font     color    =   "blue">Height:</font> %s<br>            the cookie to the user
57           <font     color    =   "blue">Favorite Color:</font>
58           <font     color    =   "%s"> %s<br>""" % (name, height, color, color)
59
60           print """<br><a href= "fig27_21.py">
61           Read cookie values</a>"""                           Calls the program in the
                                                                 next figure (fig 27.21)




      2001 Prentice Hall, Inc. All rights reserved.
                                                       Outline

                                                  fig27_20.py




 2001 Prentice Hall, Inc. All rights reserved.
1        #!C:\Python\python.exe                                                            Outline
2        # Fig. 27.21: fig27_21.py
3        # Program that retrieves and displays client-side cookie values
4
5        import Cookie                                                             fig27_21.py
6        import os
7
8        print "Content-type: text/html"
9        print
10
11       print """<body background = "images/back.gif">
12       <basefont face = "arial, sans-serif" size = "3">"""
13
14       try:                                                 Retrieves   the cookie for reading
15          cookie = Cookie.Cookie()
16          cookie.load( os.environ[ "HTTP_COOKIE" ] )
17       except KeyError:
18          print """<strong>Error reading cookies</strong>"""
19       else:
20          print """<strong>The following data is saved in a cookie
21          on your computer.</strong><br><br>"""
22
23           print """<table border = "5" cellspacing = "0"
24              cellpadding = "10">"""
25
26           for item in cookie.keys():
27              print """<TR>
28                 <td bgcolor = "#AAAAFF">%s</td>               Retrieves each value in the cookie
29                 <td bgcolor = "#AAAAAA">%s</td>               and displays it out to the user
30              </tr>""" % ( item, cookie[ item ].value )
31
32           print """</TABLE>"""



      2001 Prentice Hall, Inc. All rights reserved.
                                                       Outline

                                                  fig27_21.py




 2001 Prentice Hall, Inc. All rights reserved.
             27.9 Database Application Programming
                      Interface (DB-API)
      • Python Database Special Interest Group (SIG)
              – Developed specifications for DB-API
              – Only modules that conform to the specifications are allowed
                to be shared with other programmers
              – Allows for code reuse




 2001 Prentice Hall, Inc. All rights reserved.
                                                  27.9.1 Setup

      • Programming
              – Need to install MySQL or Microsoft Access
              – Must install win32all and MySQLdb extensions




 2001 Prentice Hall, Inc. All rights reserved.
                      27.9.2 A Simple DB-API Program

      • Database
              – Must select the database to query
              – Execute query stings on databases




 2001 Prentice Hall, Inc. All rights reserved.
1        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">                  Outline
2        <!-- Fig. 27.22: fig27_22.html -->
3
4        <html>
5           <head>                                                                fig27_22.py
6               <title>Database query</title>
7           </head>
8
9        <body background = "images/back.gif">
10       <basefont face = "arial,sans-serif" size = "2">
11
12           <font size = "+2">
13              <strong>Enter a search string and click Find.</strong>
14           </font><br>
15
16          <form method = "post" action = "cgi-bin/fig27_23.py">
17             <input type = "text" name = "search"><br>
18             <input type = "submit" value = "Find"><br>
19             <input type = "radio" name = "database"          Creates a textbox, a button, and
20                value = "MySQL" checked>                      a radio button to allow the user
21             MySQL
22             <input type = "radio" name = "database"
                                                                to enter a search and find it
23                value = "Access">
24             Microsoft Access
25          </form>
26       </body>
27       </html>




      2001 Prentice Hall, Inc. All rights reserved.
                                                                                                                 Outline

                                                                                                            fig27_22.py




Netscape Communicator browser window ©1999 Netscape Communications Corporation. Used with
permission. Netscape Communications has not authorized, sponsored, endorsed, or approved this publication
and is not responsible for its content.




 2001 Prentice Hall, Inc. All rights reserved.
1        #!c:\Python\python.exe                                                                           Outline
2        # Fig. 27.23: fig27_23.py
3        # A program to illustrate Python's database connectivity.
4
5        import cgi                                                                              fig27_23.py
6
7        def printContent():
8            print "Content-type: text/html"
9            print
10
11       def getConnection( databaseType, databaseName ):
12           connection = None
13                                                                   Depending on the radio button
14             if databaseType == 'MySQL':                           chosen, the correct db is imported
15                 import MySQLdb
16                 connection = MySQLdb.connect( db = databaseName )
17             elif databaseType == 'Access':
18                 import odbc
19                 connection = odbc.odbc( databaseName )
20
21             return connection
22
23       # get results from form                   Gets the user entered data from the
24       form = cgi.FieldStorage()                 form and stores them in variables
25
26       printContent()                                      # print HTML header
27
28       try:
29             queryString = form[ "SEARCH" ].value
30             database = form[ "DATABASE" ].value




      2001 Prentice Hall, Inc. All rights reserved.
31       except:
32           print """<font color = "red" size = "+2">                                          Outline
33             FORM ERROR</font><br>
34             You did not enter a query string.<br>
35             <font color = "blue"> Click the Back button,                                fig27_23.py
36             fill out the form and resubmit.<br><br>
37             Thank You.</font>"""
38       else:
39
40             # connect to database and get cursor
41             connection = getConnection( database, "Deitel" )
42             cursor = connection.cursor()
43                                                           Cursors are used to execute
                                                            Tried to run the query
44             try:                                          queries on entered
                                                            that the userthe database
45                 cursor.execute( queryString )   # execute user's query
46             except:
47                 print """An error occurred in your query statement."""
48             else:
49                 results = cursor.fetchall()     # store results in list
50
51                    # display results
52                    print """Database used: <font color = "blue">
53                    %s</font><br>""" % database
54                    print """<table border = "1" cellpadding = "3">"""
55
56                    for row in results:                Creates a table to
57                        print "<tr>"
58                                                       display the results
59                         for entry in row:
60                             print "<td>%s</td>" % entry
61
62                    print """</table>"""
63
64            cursor.close()                           # close cursor
65            connection.close()                       # close connection
      2001 Prentice Hall, Inc. All rights reserved.
                                                                                                        Outline

                                                                                                   fig27_23.py




   Netscape Communicator browser window ©1999 Netscape Communications Corporation. Used with
   permission. Netscape Communications has not authorized, sponsored, endorsed, or approved this
   publication and is not responsible for its content.



 2001 Prentice Hall, Inc. All rights reserved.
                 27.10 Object-Oriented Programming

      • Object-oriented programming
              – The class keyword is used to start a class
              – The def keyword is used to declare methods
                     • The first parameter of every Python method has to be an object
                       to reference the data and methods of that class




 2001 Prentice Hall, Inc. All rights reserved.
1        # Fig: 27.24: Employee.py                                                                 Outline
2        # An employee class
3                                                      The beginning of class Employee
4        class Employee:
5           def __init__( self, first, last ):                                                  fig27_24.py
6              self.firstName = first                         The first parameter, self, is a reference
7              self.lastName = last
8                                                             to the other methods in the class
9            def __str__( self ):
10              return "%s, %s" % ( self.lastName, self.firstName )



                             self is used to set and get the data members




      2001 Prentice Hall, Inc. All rights reserved.
1        # Fig. 27.25: Hourly.py                                                                       Outline
2        # An hourly employee class                    The inherited class is imported
3
4        import Employee                                      This is used to show that class hourly
5                                                             inherits from class Employee          fig27_25.py
6        class Hourly( Employee.Employee ):
7
8              def __init__( self, first, last, initHours, initWage ):
9                  Employee.Employee.__init__( self, first, last )
10                 self.hours = initHours
11                 self.wage = initWage
12                                                                     Sets the values of the
13             def __str__( self ):                                    inherited Employee class
14                 return "%s, %s is an hourly worker with pay of $%.2f." \
15                     % ( self.lastName, self.firstName, self.getPay())
16
17             def getPay( self ):
18                 return self.hours * self.wage

Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> import Employee
>>> employee = Employee.Employee( "Jane", "Doe" )
>>> import Hourly
>>> hourly = Hourly.Hourly( "John", "Doe", 20, 20.00 )
>>> workerList = [ employee, hourly ]
>>> for item in workerList:
...     print item
...
Doe, Jane
Doe, John is an hourly worker with pay of $400.00.
>>>



      2001 Prentice Hall, Inc. All rights reserved.
       27.11 Case Study: GUI Database Application

      • GUI
              – Again it is assumed that the user knows a good deal about
                GUIs before reading the section




 2001 Prentice Hall, Inc. All rights reserved.
                                                  27.11.1 Gadfly

      • Gadfly database
              – A relational database written entirely in Python
              – Supports a significant subset if SQL
              – Conforms to the Python DB-API specifications




 2001 Prentice Hall, Inc. All rights reserved.
                                                  27.11.1 Gadfly

Button to open a                                                   Button to close the
selected database.                                                 current database.


        List of
        available
        databases.
                                                                       Window that
                                                                       displays results of
                                                                       the SQL query.
        List of available
        tables in the
        currently open
        database.
                                                                     Button to execute
        SQL statement                                                SQL statement on
        entry box.                                                   currently open
                                                                     database.

        Fig. 27.26 Database GUI viewer. (Courtesy of Tcl/Tk.)


 2001 Prentice Hall, Inc. All rights reserved.
                                            27.11.2 Tkinter

      • Tk
              – A GUI extension to the scripting language Tcl
              – All Tkinter objects inherit from class Widget
      • The Python module Pmw
              – Used to create mega widgets
                     • Combine the functionality of several Tk widgets




 2001 Prentice Hall, Inc. All rights reserved.
                                                  27.11.3 Setup

      • Setup
              – In order to work properly the Tkinter and Pmw modules
                must be downloaded and installed




 2001 Prentice Hall, Inc. All rights reserved.
           27.11.4 Database Viewer Implementation

      • from/import
              – Allow the importing from a certain class without the use of
                the dot operator (.).




 2001 Prentice Hall, Inc. All rights reserved.
1        # Fig. 27.27: DatabaseViewer.py                                                                  Outline
2        # A GUI Database Viewer
3
4        import os, string
5        import glob                                                                               fig27_27.py
6        from Tkinter import *
                                                           Used to import from a sub
7        import tkMessageBox                               class Tkinter and
8        import Pmw                                        gadfly
9        from gadfly import gadfly
10
11       class DatabaseViewer( Frame ):
12
13           def __init__( self ):
                                                                    Sets the data members
14              Frame.__init__( self )
15
16                self.gadflyPath = "C:\\Python\\Gadfly" # path to database
17                self.databaseDirectories = {} # database locations
18                self.databaseNames = []       # list of available databases
19                self.connection = None        # connection to database
20                self.currentQuery = StringVar() # current query string
21                self.queryDisplay = None         # query results text dialog
22
23                # populate databaseNames list
24                os.path.walk( self.gadflyPath, self.getDatabase, 0 )
25
26                # configure master
27                self.master.title( 'Database GUI Viewer' )                        Get the all the database names
28                self.master.columnconfigure( 0, weight = 1 )
29                self.master.rowconfigure( 0 , weight = 1 )
30                self.master.grid()                                            Sets up the parent of
31                                                                              the database viewer
32                # build GUI components
33                self.buildGUI()
34                                                     Constructs the GUI
      2001 Prentice Hall, Inc. All rights reserved.
35           def destroy( self ):                                                                 Outline
36              self.closeDatabase()                   Closes the database
37              Frame.destroy( self )
38
                                                       and the GUI
39           def getDatabase( self, path, dirname, names ):                             fig27_27.py
40              """Get names of all databases in specified directory."""
41              os.chdir( dirname )     # change directories
42
43                # get list of all database files in gadfly directory
44                databaseFiles = glob.glob( "*.gfd" )
45
46                for database in databaseFiles:                Gets all     files of type .gdf
47                   databaseName = database[ :-4 ]
48                   self.databaseNames.append( databaseName )                Gets the database name minus
49                   self.databaseDirectories[ databaseName ] = dirname       the .gdf and adds it to the list
50
51           def createSection( self, parent, labelText, numberOfColumns ):
52              """Creates a subsection of a frame."""
53
54                # create enclosing frame
55                frame = Frame( parent, relief = 'groove', borderwidth = 5 )
56                frame.columnconfigure( tuple( range( numberOfColumns ) ),
57                   weight = 1 )
58                                                                           Constructs the frame and sets
59                # create label for frame
60                label = Label( frame, text = labelText,               it column numbers into a tuple
61                   font = ( 'Arial', 12, 'bold' ), background =
62                   'dark gray', foreground = 'dark blue', relief = 'ridge',
63                   borderwidth = 3 )
64                label.grid( row = 0, columnspan = numberOfColumns,
65                   sticky = 'new' )                                   Creates a label for the frame
66
67                return frame
68

      2001 Prentice Hall, Inc. All rights reserved.
69        def createButton( self, parent, name, action, gridRow,                         Outline
70           gridColumn ):
71           """Creates a button."""
72           return Button( parent, text = name, command = action ) \
73              .grid( row = gridRow, column = gridColumn )                      fig27_27.py
74
                                                                  Create a button by sending it the
75        def buildGUI( self ):                                   name, its parent, its action, and
76           """Build database viewer display."""                 where on the form it is located
77
78             #------------------Configure self-----------------------#
79             Pmw.initialise()
80             self.grid( row = 0, column = 0, sticky = 'nesw' )
81             #-------------------------------------------------------#
82
83             #-------------Build 'Select Database' Section-----------#
84             databaseFrame = self.createSection( self,
85                "Select Database", 3 )
86             databaseFrame.grid( row = 0, column = 0, sticky = 'nesw',
87                columnspan = 2 )
88                                                                      Creates a combo box to
89             # allows users to select from databases
                                                                        allow the database choice
90             self.databaseComboBox = Pmw.ComboBox( databaseFrame,
91                scrolledlist_items = self.databaseNames, dropdown = 1 )
92             self.databaseComboBox.grid( row = 1, column = 0, padx = 3,
93                sticky = 'e' )
94
95             # button to open selected database
96             openDatabaseButton = self.createButton( databaseFrame,
97                "Open Database", self.openDatabase, 1, 1 )
98
99             # button to close current database
100            closeDatabaseButton = self.createButton( databaseFrame,
101               "Close Database", self.closeDatabase, 1, 2 )
102            #-------------------------------------------------------#

   2001 Prentice Hall, Inc. All rights reserved.
103                                                                                        Outline
104            #------------Build 'Table Information' Section----------#
105            tableFrame = self.createSection( self,
106               "Table Information", 2 )
107            tableFrame.grid( row = 1, column = 0, columnspan = 2,              fig27_27.py
108               sticky = 'nesw', pady = 5 )                       Creates   a label to generate
109
110            # List of available tables                           the list of databases
111            Label( tableFrame, text = "Available Tables:", relief =
112               'raised' ).grid( row = 1, column = 0, sticky = 'nesw' )
113            self.tableList = Pmw.ScrolledListBox( tableFrame,
114               selectioncommand = self.displayColumnInfo )
115            self.tableList.configure( listbox_height = 11 )
116            self.tableList.grid( row = 2, column = 0, sticky = 'nesw' )
117                                                                           A label that will display
118            # Information about selected table
                                                                              information about the
119            Label( tableFrame, text = "Column Names:", relief =
120               'raised' ).grid( row = 1, column = 1, sticky = 'nesw' )     selected table
121            self.tableDisplay = Pmw.ScrolledText( tableFrame,
122               text_wrap = 'none' )
123            self.tableDisplay.configure( text_height = 13 )
124            self.tableDisplay.configure( text_width = 50 )
125            self.tableDisplay.grid( row = 2, column = 1,
126               sticky = 'nesw' )
127            #--------------------------------------------------------#
128
129            #-----------Build 'Query Statement' Section--------------#
130            queryFrame = self.createSection( self,
131               "Query Statement:", 1 )
132            queryFrame.grid( row = 2, column = 0, sticky = 'nesw',
133               columnspan = 2 )
134



   2001 Prentice Hall, Inc. All rights reserved.
135            # Entry field for query statement                                         Outline
136            self.queryEntry = Pmw.EntryField( queryFrame,         Creates the area where the query
137               command = self.executeQuery, entry_textvariable = will be entered by the user
138               self.currentQuery )
139            self.queryEntry.grid( row = 1, column = 0, sticky = 'ew',         fig27_27.py
140               pady = 5 )
141
142            # Button to execute statement
143            queryExecuteButton = self.createButton( queryFrame,
144               "Execute Query", self.executeQuery, 2, 0 )
145            #-------------------------------------------------------#
146
147       def openDatabase( self ):
148          """Open selected database."""
149
150            if self.connection:
151               tkMessageBox.showerror( "Database already open",
152                  "You must close the current database before "
153                  + "opening a new one." )
154               return
155
156            # open database                      Tries to open the database for use
157            try:
158
159               # get path to specified database
160               databaseName = self.databaseComboBox.get()
161               databasePathname = os.path.join( self.gadflyPath,
162                  self.databaseDirectories[ databaseName ] )
163               self.connection = gadfly( databaseName,
164                  databasePathname )
165            except KeyError:
166               tkMessageBox.showerror( "Select Database",
167                  "You must first select a database to open." )
168               return

   2001 Prentice Hall, Inc. All rights reserved.
169            except:                                                                     Outline
170               tkMessageBox.showerror( "Database Error",
171                  "Error opening database." )
172               return                          Runs the query     in the database
173                                                                                  fig27_27.py
                                                    to obtain the table information
174            # get table info
175            cursor = self.connection.cursor()
176            cursor.execute( "select * from __table_names__" )
177            results = cursor.fetchall()
178
179            # display list of tables
180            for item in results:
181               self.tableList.insert( 0, item[ 1 ] )       Displays the table
182
183            cursor.close()
184
185       def displayColumnInfo( self ):
186          """Display columns from selected table."""
187
188            if self.connection == None:
189               return
                                                            Retrieves a record from the table
190
191            # get a record from this table
192            tableName = self.tableList.getcurselection()
193            cursor = self.connection.cursor()
194            cursor.execute( "select * from %s" % tableName )
195            results = cursor.description
196
197            # display column information
198            self.tableDisplay.clear()
199




   2001 Prentice Hall, Inc. All rights reserved.
200            for row in results:                                                           Outline
201               self.tableDisplay.insert( END, row[ 0 ] + '\n' )
202
203            cursor.close()
204                                                                                 fig27_27.py
205       def executeQuery( self ):
206          """Execute user-entered query statement."""
207
208            # user must open database to execute query                Makes sure that a
209            if self.connection == None:                               database is opened first
210               tkMessageBox.showerror( "Open Database",
211                  "You must first select and open a database." )
212               return
213
214            cursor = self.connection.cursor()
215
216            # execute query, raise exception on error
217            try:
218               queryString = self.currentQuery.get() # retrieve string
219               queryString = queryString.replace( '"', "'" )            Executes the query and
220               cursor.execute( queryString )                            checks for any errors
221               results = cursor.pp()
222            except Exception, errorMessage:
223               results = "The SQL statement cannot be executed.\n" \
224                  + "The full SQL error message is:\n\n%s" \
                                                                  The pp method is used to format
225                  % errorMessage
226                                                                  the list to be easily readable
227            # display results in new window
228            if self.queryDisplay:
229               self.queryDisplay.destroy()
230




   2001 Prentice Hall, Inc. All rights reserved.
231            self.queryDisplay = Pmw.TextDialog( title =                                    Outline
232               "Results for: %s" % queryString, defaultbutton = 0 )
233            self.queryDisplay.configure( text_height = 10 )
234            self.queryDisplay.configure( text_width = 50 )
235            self.queryDisplay.insert( END, results )                              fig27_27.py
236            self.queryDisplay.configure( text_state = "disabled" )
237            self.queryDisplay.activate( globalMode = 'nograb' )
238
239            cursor.close()
240
241       def closeDatabase( self ):
242          """Close current database."""
243
244            if self.connection == None:
245               return
246
247            # close connection and clear display fields
248            self.connection.close()
                                                       Close    the database
249            self.connection = None
250            self.databaseComboBox._entryfield.clear()
251            self.tableList.clear()
252            self.tableDisplay.clear()
253
254   if __name__ == "__main__":                    Checks to see if the current namespace is
255      DatabaseViewer().mainloop()                __main__, if true the file runs as a script
                                                    rather than imported by another file




   2001 Prentice Hall, Inc. All rights reserved.
                     27.12 Operator Precedence Chart

      • Precedence
              – The operators in the next slide (fig. 27.28) shows the
                operators in order of precedence from the top to the bottom




 2001 Prentice Hall, Inc. All rights reserved.
                     27.12 Operator Precedence Chart

       Op e ra to r                         Typ e                           Asso c ia tivity
       ‘ ‘                                  string conversion               left to right
      { }                             dictionary creation                   left to right
      [ ]                             list creation                         left to right
      ( )                             tuple creation                        left to right
      [ : ]                           slicing                               left to right
      [ ]                             subscript access                      left to right
      .                               member access                         left to right
      ~                               bitwise not                           left to right
      +                               unary plus                            right to left
      -                               unary minus
      **                              exponentiation                        left to right
      Fig. 27.28           Pytho n o p e ra to r p rec ed e nc e c ha rt.




 2001 Prentice Hall, Inc. All rights reserved.
                     27.12 Operator Precedence Chart

         Op era tor                   Typ e                      Assoc ia tivity
         *                            multiplication             left to right
         /                            division
         %                            modulus (remainder)
         +                            addition                   left to right
         -                            subtraction
         <<                           left shift                 left to right
         >>                           right shift
         &                            bitwise AND                left to right
         ^                            bitwise XOR                left to right
         |                            bitwise OR                 left to right
         <                            less than                  right to left
         <=                           less than or equal
         >                            greater than
         >=                           greater than or equal
         <>, !=                       not equal
         ==                           equal
         Fig. 27.28          Python operator precedence chart.

 2001 Prentice Hall, Inc. All rights reserved.
                     27.12 Operator Precedence Chart

        Op e ra to r             Typ e                                      Asso c ia tivity
        is, is not               identity                                   left to right
        in, not in               membership tests                           left to right

        not                      boolean NOT                                left to right
        and                      boolean AND                                left to right


        or                       boolean OR                                 left to right

        lambda                   lambda expressions (anonymous functions)   left to right

        Fig. 27.28            Python operator precedence chart.




 2001 Prentice Hall, Inc. All rights reserved.
                   27.13 Internet and World Wide Web
                               Resources




 2001 Prentice Hall, Inc. All rights reserved.

								
To top