Week 3,4,5

Part 2 Programming Exercise

  1. Client.py
    
    class Client(object):
        '''
        Client class to represent each customer object
        '''
        numClient = 0 # class variable to record number of client
        
        def __init__(self,name,address,balance ):
            '''
            constructor method
            
            Parameters:
    
            - name: name of customer
            - address: name of customer
            - balance: balance of customer
            '''
            Client.numClient += 1
            
            self.name = name
            self.address = address
            self.__balance = balance
        
        def debit(self,amount):
            '''
            debit method to increase balance of liability account
            
            Parameters:
    
            - amount: amount to bebit     
            '''
            self.__balance += amount
            
        def credit(self,amount):
            '''
            credit method to increase balance of liability account
            
            Parameters:
    
            - amount: amount to credit     
            '''
            self.__balance -= amount
            
        def getBalance(self):
            '''
            accessor method to get balance
            '''
            return self.__balance
            
        def __str__(self):
            '''
            String representation of client object
            '''
            return '%-20s%-30s%10.2f\n'%\
                (self.name,self.address,self.__balance)
    
    GUIsb.py
    
    import tkinter as tk
    import tkinter.scrolledtext as tkst
    from quitButton import quitButton
    from Client import Client
    
    class Gui:
            
        def __init__(self, root):
            self.root = root
            self.root.title("Simple Billing System")
            self.root.geometry('600x400')
            self.editArea = tkst.ScrolledText(self.root,height=5)
            self.editArea.pack(expand=1, fill="both") 
    
            self.menuChoice = tk.IntVar()
            self.menuChoice.set(0)
            menuItems = [('Display transaction data',1),
                        ('Display customer table',2)]
            
            for (val, item) in enumerate(menuItems):
                tk.Radiobutton(self.root, 
                      text=item[0],
                      variable=self.menuChoice,
                      command=self.showChoice,
                      value=val).pack(anchor=tk.W)
    
            self.btnQ = quitButton(self.root) 
            self.showData()
            
            
        def showChoice(self):
            if self.menuChoice.get() == 1:
                self.simpleBilling()
            elif self.menuChoice.get() == 0:
                self.showData()
            
        def simpleBilling(self):
            
            fileIn = open('datafile1.dat', 'r')
    
            clientDT=['Name','Address','Balance']
            clientDL=[]
            Client.numClient = 0
            line = fileIn.readline()
    
            while line != '':
                clientRec=line.split('_')
            
                if Client.numClient == 0:
                    if clientRec[2] == 'D':
                        clientDL.append(Client(clientRec[0],
                                               clientRec[1],
                                               float(clientRec[3])))
                    else:
                        clientDL.append(Client(clientRec[0],
                                               clientRec[1],
                                               -float(clientRec[3])))           
                else: 
                    i = 0
                    while i < Client.numClient and clientDL[i].name != clientRec[0]:
                        i += 1
                
                    if i == Client.numClient:
                        if clientRec[2] == 'D':   
                            clientDL.append(Client(clientRec[0],
                                               clientRec[1],
                                               float(clientRec[3])))
                        else:
                            clientDL.append(Client(clientRec[0],
                                               clientRec[1],
                                               -float(clientRec[3])))                
                    else:
                        if clientRec[2] == 'D':
                            clientDL[i].debit(float(clientRec[3]))
                        else: clientDL[i].credit(float(clientRec[3])) 
                
                line = fileIn.readline()
                
            self.editArea.delete(1.0, tk.END)    
            self.editArea.insert(tk.INSERT,('%-20s%-30s%10s\n'%(clientDT[0],clientDT[1],clientDT[2])))
            self.editArea.insert(tk.INSERT,'='*60+'\n')    
            for e in sorted(clientDL, key = lambda c: c.name):
                if e.getBalance() != 0:
                    self.editArea.insert(tk.INSERT,e) 
              
            fileIn.close() 
             
        def showData(self):
            
            fileIn = open('datafile1.dat', 'r')
    
            line = fileIn.readline()
            self.editArea.delete(1.0, tk.END)    
            self.editArea.insert(tk.INSERT,('%-20s%-30s%5s%10s\n'%('Name',
                                                                    'Address',
                                                                    'Txn',
                                                                    'Amount')))
            self.editArea.insert(tk.INSERT,'='*65+'\n') 
                
            while line != '':
                clientRec=line.split('_')
    
                self.editArea.insert(tk.INSERT,('%-20s%-30s%5s%10.2f\n'%(clientRec[0],
                                                                    clientRec[1],
                                                                    clientRec[2],
                                                                    float(clientRec[3]))))
                line = fileIn.readline()
    
            fileIn.close()       
    
    def main():
        root = tk.Tk()
        Gui(root)
        root.mainloop()
    
    if __name__ == '__main__':
        main()
    
    
  2. pydbsb.py

    
    #!%python_path%python.exe
    import time
    import pymysql
    import urllib.request
    
    fileIn=urllib.request.urlopen('http://personal.cityu.edu.hk/~dcywchan/2004dco10803/datafile1.txt')
    byteStr = fileIn.read()
    lines=byteStr.decode('utf-8')
    lineSep=lines.split('\r\n')
    
    html5top='''
    <!-- {fname} -->
    <!DOCTYPE html>
    <html>
     <head>
      <title>{title}</title>
     </head>
     <body>
      <h1>{header}</h1>
    '''
    html5bottom='''
     </body>
    </html>
    '''
    tableHeader='''
    <table border=1>
    <tr><th>Name</th><th>Address</th><th>Balance</th></tr>
    '''
    print (html5top.format(fname='pydbsb.py',title='pymysql',header='Customer Table'))
    
    connection = pymysql.connect(user='root',
                                 password='',
                                 db='simplebilling', 
                                 cursorclass=pymysql.cursors.DictCursor)
    
    print('<h2>Before Transactions</h2>')
    print(tableHeader)
    with connection.cursor() as cursor:
        cursor.execute('SELECT name,address,balance from customers')
        for e in cursor.fetchall():
            print ('<tr><td>'+e['name']+'</td>'+
                   '<td>'+e['address']+'</td>'+
                   '<td>'+str(e['balance'])+'</td></tr>')
    
    print('</table>')
    
    for e in lineSep:
        if e != '':
            clientRec=e.split('_')
            cursor = connection.cursor()
            cursor.execute('SELECT name FROM customers where name = \'%s\';'%clientRec[0])
            data = cursor.fetchone()
            if data == None:
                cursor.execute('''INSERT INTO customers (name,address,balance) VALUES 
                               ( \'%s\',\'%s\',\'%s\');'''%(clientRec[0],clientRec[1],clientRec[3]))
            else: 
                if clientRec[2] == 'D':
                    cursor.execute('''UPDATE customers
                                SET balance = balance + %f
                                WHERE name = \'%s\';'''%(float(clientRec[3]),clientRec[0]))
                else: cursor.execute('''UPDATE customers 
                               SET balance = balance - %f
                               WHERE name = \'%s\';'''%(float(clientRec[3]),clientRec[0]))
                
    print('<h2>After Transactions</h2>')
    print(tableHeader)
    with connection.cursor() as cursor:
        cursor.execute('''SELECT name,address,balance from customers
                       ORDER BY name''')
        for e in cursor.fetchall():
            print ('<tr><td>'+e['name']+'</td>'+
                   '<td>'+e['address']+'</td>'+
                   '<td>'+str(e['balance'])+'</td></tr>')
    
    print('</table>')
    
    connection.close()
    print (time.ctime( time.time() ))
    print (html5bottom)
    
    
  3. pydbsbsort.py

    
    #!%python_path%python.exe
    import time
    import pymysql
    import cgi
    
    html5top='''
    <!-- {fname} -->
    <!DOCTYPE html>
    <html>
     <head>
      <title>{title}</title>
     </head>
     <body>
      <h1>{header}</h1>
    '''
    html5bottom='''
     </body>
    </html>
    '''
    tableHeader='''
    <table border=1>
    <tr><th>Name</th><th>Address</th><th>Balance</th></tr>
    '''
    
    form = cgi.FieldStorage()
    if 'sortBy' in form:
        sortBy = form[ 'sortBy' ].value
    else:
        sortBy = 'name'
       
    if 'sortOrder' in form:
        sortOrder = form[ 'sortOrder' ].value
    else:
        sortOrder = 'ASC'   
       
    print (html5top.format(fname='pydbsb.py',title='pymysql',header='Customer Table'))
    
    connection = pymysql.connect(user='root',
                                 password='',
                                 db='simplebilling', 
                                 cursorclass=pymysql.cursors.DictCursor)
    
    print(tableHeader)
    with connection.cursor() as cursor:
        cursor.execute('SELECT * from customers ORDER BY %s %s' %
                       ( sortBy, sortOrder ))
        allFields = cursor.description
        for e in cursor.fetchall():
            print ('<tr><td>'+e['name']+'</td>'+
                   '<td>'+e['address']+'</td>'+
                   '<td>'+str(e['balance'])+'</td></tr>')
    
    print('</table>')
    print('<hr>')
    
    print ('''
          \n<form method = 'post' action = '/cgi-bin/pydbsbsort.py'>
          Sort By:<br />''')
    
    for field in allFields:
        print ('''<input type = 'radio' name = 'sortBy'
          value = '%s' />''' % field[ 0 ])
        print (field[ 0 ])
        print ("<br />")
    
    print ('''<br />\nSort Order:<br />
          <input type = 'radio' name = 'sortOrder'
          value = 'ASC' checked = 'checked' />
          Ascending
          <input type = 'radio' name = 'sortOrder'
          value = 'DESC' />
          Descending
          <br /><br />\n<input type = 'submit' value = 'SORT' />
          </form>\n\n</body>\n</html>''')
     
    
    connection.close()
    print (time.ctime( time.time() ))
    print (html5bottom)
    
    

    pydbsbsearch.py

    
    #!%python_path%python.exe
    import time
    import pymysql
    import cgi
    
    html5top='''
    <!-- {fname} -->
    <!DOCTYPE html>
    <html>
     <head>
      <title>{title}</title>
     </head>
     <body>
      <h1>{header}</h1>
    '''
    html5bottom='''
     </body>
    </html>
    '''
    tableHeader='''
    <table border=1>
    <tr><th>Name</th><th>Address</th><th>Balance</th></tr>
    '''
    
    form = cgi.FieldStorage()
    if 'searchBy' in form:
        searchBy = form[ 'searchBy' ].value
    else:
        searchBy = 'name'
        
    if 'searchKey' in form:  
        searchKey = form.getvalue('searchKey')
    else:
        searchKey = '%'
       
    print (html5top.format(fname='pydbsbsearch.py',title='pymysql',header='Customer Table'))
    
    connection = pymysql.connect(user='root',
                                 password='',
                                 db='simplebilling', 
                                 cursorclass=pymysql.cursors.DictCursor)
    
    print(tableHeader)
    with connection.cursor() as cursor:
        cursor.execute('SELECT * from customers WHERE %s LIKE \'%s\'' %
                       ( searchBy, searchKey ))
        allFields = cursor.description
        for e in cursor.fetchall():
            print ('<tr><td>'+e['name']+'</td>'+
                   '<td>'+e['address']+'</td>'+
                   '<td>'+str(e['balance'])+'</td></tr>')
    
    print('</table>')
    print('<hr>')
    
    print ('''
          \n<form method = 'post' action = '/cgi-bin/pydbsbsearch.py'>
          Search By:<br />''')
    
    for field in allFields:
        print ('''<input type = 'radio' name = 'searchBy'
          value = '%s' />''' % field[ 0 ])
        print (field[ 0 ])
        print ("<br />")
    
    print ('''<br />Search Key:<br />
          <input type = 'text' name = 'searchKey'
          value = '' />
          <br /><br />\n<input type = 'submit' value = 'Search' />
          </form>\n\n</body>\n</html>''')
     
    
    connection.close()
    print (time.ctime( time.time() ))
    print (html5bottom)