├── ch20 ├── alt │ ├── cgihttpd2.py │ ├── cgihttpd.py │ ├── friends1.py │ ├── myhttpd.py │ ├── friends2.py │ ├── friends3.py │ ├── advcgi.py │ └── advcgi2.py ├── uniCGI.py ├── friends1.py ├── friends.htm ├── urlopenAuth.py ├── myhttpd.py ├── friends2.py ├── friends3.py ├── crawl.py └── advcgi.py ├── ch16 ├── alt │ ├── ts.zip │ ├── tsTclntSSBRH.py │ ├── tsTclntNew.py │ ├── tsTservSS.py │ ├── tsTservSSBRH.py │ ├── tsUserv.py │ ├── tsTserv.py │ └── tsTservNew.py ├── tsUclnt.py ├── tsTclnt.py ├── tsTclntSS.py ├── tsUserv.py ├── tsTservSS.py ├── tsTservTW.py ├── tsTserv.py └── tsTclntTW.py ├── ch14 ├── alt │ ├── xcount.py │ └── loopmake.py ├── args.py ├── funcAttrs.py └── loopmake.py ├── ch19 ├── tkhello1.py ├── tkhello2.py ├── tkhello3.py ├── alt │ ├── tkhello0.py │ ├── tkhello2.py │ ├── tkhello1.py │ ├── tkhello4.py │ └── listdir.py ├── tkhello4.py ├── animalTix.pyw ├── animalPmw.pyw ├── pfaGUI2.py ├── animalWx.pyw ├── animalGtk.pyw └── listdir.py ├── ch10 ├── carddata.txt ├── cardlog.txt ├── cardrun.py ├── alt │ ├── cardrun.py │ └── myexc.py └── myexc.py ├── ch22 ├── setup.py ├── Extest1.c └── Extest2.c ├── ch11 ├── alt │ ├── simpleGen.py │ ├── randGen.py │ ├── counter.py │ ├── scope.py │ └── deco.py ├── numConv.py ├── deco.py ├── scope.py ├── pfaGUI.py ├── grabWeb.py ├── testit.py ├── closureVars.py ├── funcLog.py └── easyMath.py ├── ch15 ├── rewho.py ├── alt │ ├── rewho.py │ └── gendata.py └── gendata.py ├── ch06 ├── alt │ ├── stringTemplates.py │ ├── NoneIndex.py │ ├── insertVsColonZero.py │ ├── idcheck2.py │ ├── reversedSorted.py │ ├── idcheck.py │ ├── stack.py │ └── queue.py ├── uniFile.py ├── buggy.py ├── idcheck.py ├── queue.py └── stack.py ├── ch13 ├── randSeq.py ├── roundFloat2.py ├── capOpen.py ├── hotel.py ├── anyIter.py ├── alt │ ├── metaIntro.py │ ├── anyIter.py │ ├── hotel.py │ ├── capOpen.py │ ├── descr-tef.py │ ├── descr-with.py │ ├── twrapme.py │ ├── descr.py │ └── moneyfmt.py ├── time60.py ├── moneyfmt.py ├── ProtectAndHideX.py ├── descrPRE25.diff ├── descr.diff ├── twrapme.py ├── meta.py ├── descr.py ├── descr0.py ├── descrPRE25.py └── numstr.py ├── ch08 ├── maxFact.py └── alt │ └── maxFact.py ├── ch04 └── typechk.py ├── ch03 ├── readTextFile.py ├── makeTextFile0.py ├── makeTextFile.py ├── makeTextFile.diff └── makeTextFile1.py ├── ch18 ├── onethr.py ├── myThread.py ├── mtsleep1.py ├── mtsleep3.py ├── mtsleep2.py ├── mtsleep5.py ├── mtsleep4.py ├── mtfacfib.py ├── prodcons.py └── alt │ └── mtfacfib.py ├── ch23 ├── swhello.py ├── stock.py ├── excel.pyw ├── word.pyw ├── ppoint.pyw ├── olook.pyw ├── swhello.java ├── alt │ └── win32demo.pyw └── estock.pyw ├── .gitignore ├── ch17 ├── myMail.py ├── getLatestFTP.py └── getLatestNNTP.py ├── ch07 ├── userpw.py └── alt │ └── userpw.py ├── README.md ├── ch09 ├── ospathex.py └── alt │ └── ospathex.py └── ch21 ├── ushuffle_so.py ├── ushuffle_sa.py ├── ushuffle_db.py └── alt └── ushuffle_dbPRE25.py /ch20/alt/cgihttpd2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from CGIHTTPServer import test;test() 4 | -------------------------------------------------------------------------------- /ch16/alt/ts.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gexos/Core-Python-Programming-2nd-Edition-Examples-and-Source-Code/HEAD/ch16/alt/ts.zip -------------------------------------------------------------------------------- /ch14/alt/xcount.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | x = 0 4 | print 'x is currently:', x 5 | while x < 5: 6 | x += 1 7 | print 'incrementing x to:', x 8 | -------------------------------------------------------------------------------- /ch19/tkhello1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import Tkinter 4 | 5 | top = Tkinter.Tk() 6 | label = Tkinter.Label(top, text='Hello World!') 7 | label.pack() 8 | Tkinter.mainloop() 9 | -------------------------------------------------------------------------------- /ch10/carddata.txt: -------------------------------------------------------------------------------- 1 | # carddata.txt 2 | previous balance 3 | 25 4 | debits 5 | 21.64 6 | 541.24 7 | 25 8 | credits 9 | -25 10 | -541.24 11 | finance charge/late fees 12 | 7.30 13 | 5 14 | -------------------------------------------------------------------------------- /ch22/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from distutils.core import setup, Extension 4 | 5 | MOD = 'Extest' 6 | setup(name=MOD, ext_modules=[ 7 | Extension(MOD, sources=['Extest2.c'])]) 8 | -------------------------------------------------------------------------------- /ch11/alt/simpleGen.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | def simpleGen(): 4 | yield 1 5 | yield '2 --> punch!' 6 | 7 | if __name__ == '__main__': 8 | for item in simpleGen(): 9 | print item 10 | -------------------------------------------------------------------------------- /ch15/rewho.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from os import popen 4 | from re import split 5 | 6 | f = popen('who', 'r') 7 | for eachLine in f: 8 | print split('\s\s+|\t', eachLine.strip()) 9 | f.close() 10 | -------------------------------------------------------------------------------- /ch19/tkhello2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import Tkinter 4 | 5 | top = Tkinter.Tk() 6 | quit = Tkinter.Button(top, text='Hello World!', 7 | command=top.quit) 8 | quit.pack() 9 | Tkinter.mainloop() 10 | -------------------------------------------------------------------------------- /ch06/alt/stringTemplates.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from string import Template 4 | s = Template('There are ${howmany} ${lang} Quotation Symbols') 5 | print s.substitute(lang='Python', howmany=3) 6 | print s.substitute(lang='Python') 7 | print s.safe_substitute(lang='Python') 8 | raw_input() 9 | -------------------------------------------------------------------------------- /ch11/alt/randGen.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from random import randrange as rr 4 | 5 | def randGen(aList): 6 | while aList: 7 | yield aList.pop(rr(len(aList))) 8 | 9 | if __name__ == '__main__': 10 | for item in randGen(['rock', 'paper', 'scissors']): 11 | print item 12 | -------------------------------------------------------------------------------- /ch13/randSeq.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from random import choice 4 | 5 | class RandSeq(object): 6 | def __init__(self, seq): 7 | self.data = seq 8 | 9 | def __iter__(self): 10 | return self 11 | 12 | def next(self): 13 | return choice(self.data) 14 | -------------------------------------------------------------------------------- /ch20/alt/cgihttpd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from CGIHTTPServer import test 4 | 5 | if __name__ == '__main__': 6 | try: 7 | print 'Welcome to the machine...\nPress ^C once or twice to quit' 8 | test() 9 | except KeyboardInterrupt: 10 | print 'exiting server...' 11 | -------------------------------------------------------------------------------- /ch11/numConv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | def convert(func, seq): 4 | 'conv. sequence of numbers to same type' 5 | return [func(eachNum) for eachNum in seq] 6 | 7 | myseq = (123, 45.67, -6.2e8, 999999999L) 8 | print convert(int, myseq) 9 | print convert(long, myseq) 10 | print convert(float, myseq) 11 | -------------------------------------------------------------------------------- /ch06/alt/NoneIndex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | s = 'abcde' 4 | 5 | #for x,y in enumerate(s): 6 | # print s[x:], s[:x] 7 | #for i in range(len(s), -1, -1): 8 | #print s[i:], s[:i], s[i::-1], s[:i:-1] 9 | 10 | s = 'abcde' 11 | for i in [None] + range(-1, -len(s), -1): 12 | print s[:i] 13 | 14 | raw_input() 15 | -------------------------------------------------------------------------------- /ch19/tkhello3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import Tkinter 4 | top = Tkinter.Tk() 5 | 6 | hello = Tkinter.Label(top, text='Hello World!') 7 | hello.pack() 8 | 9 | quit = Tkinter.Button(top, text='QUIT', 10 | command=top.quit, bg='red', fg='white') 11 | quit.pack(fill=Tkinter.X, expand=1) 12 | 13 | Tkinter.mainloop() 14 | -------------------------------------------------------------------------------- /ch13/roundFloat2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class RoundFloatManual(object): 4 | def __init__(self, val): 5 | assert isinstance(val, float), \ 6 | "Value must be a float!" 7 | self.value = round(val, 2) 8 | 9 | def __str__(self): 10 | return '%.2f' % self.value 11 | 12 | __repr__ = __str__ 13 | -------------------------------------------------------------------------------- /ch14/args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | 5 | def usage(): 6 | print 'At least 2 arguments (incl. cmd name).' 7 | print 'usage: args.py arg1 arg2 [arg3... ]' 8 | sys.exit(1) 9 | 10 | argc = len(sys.argv) 11 | if argc < 3: 12 | usage() 13 | print "number of args entered:", argc 14 | print "args (incl. cmd name) were:", sys.argv 15 | -------------------------------------------------------------------------------- /ch11/deco.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from time import ctime, sleep 4 | 5 | def tsfunc(func): 6 | def wrappedFunc(): 7 | print '[%s] %s() called' % ( 8 | ctime(), func.__name__) 9 | return func() 10 | return wrappedFunc 11 | 12 | @tsfunc 13 | def foo(): 14 | pass 15 | 16 | foo() 17 | sleep(4) 18 | 19 | for i in range(2): 20 | sleep(1) 21 | foo() 22 | -------------------------------------------------------------------------------- /ch20/uniCGI.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | CODEC = 'UTF-8' 4 | UNICODE_HELLO = u''' 5 | Hello! 6 | \u00A1Hola! 7 | \u4F60\u597D! 8 | \u3053\u3093\u306B\u3061\u306F! 9 | ''' 10 | 11 | print 'Content-Type: text/html; charset=%s\r' % CODEC 12 | print '\r' 13 | print '
11 | You have %s friends. 12 | ''' 13 | 14 | form = cgi.FieldStorage() 15 | who = form['person'].value 16 | howmany = form['howmany'].value 17 | print reshtml % (who, who, howmany) 18 | -------------------------------------------------------------------------------- /ch16/tsUclnt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from socket import * 4 | 5 | HOST = 'localhost' 6 | PORT = 21567 7 | BUFSIZ = 1024 8 | ADDR = (HOST, PORT) 9 | 10 | udpCliSock = socket(AF_INET, SOCK_DGRAM) 11 | 12 | while True: 13 | data = raw_input('> ') 14 | if not data: 15 | break 16 | udpCliSock.sendto(data, ADDR) 17 | data, ADDR = udpCliSock.recvfrom(BUFSIZ) 18 | if not data: 19 | break 20 | print data 21 | 22 | udpCliSock.close() 23 | -------------------------------------------------------------------------------- /ch10/cardlog.txt: -------------------------------------------------------------------------------- 1 | account log: 2 | ignored: invalid literal for float(): # carddata.txt 3 | ignored: invalid literal for float(): previous balance 4 | data... processed 5 | ignored: invalid literal for float(): debits 6 | data... processed 7 | data... processed 8 | data... processed 9 | ignored: invalid literal for float(): credits 10 | data... processed 11 | data... processed 12 | ignored: invalid literal for float(): finance charge/late fees 13 | data... processed 14 | data... processed 15 | -------------------------------------------------------------------------------- /ch16/tsTclnt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from socket import * 4 | 5 | HOST = 'localhost' 6 | PORT = 21567 7 | BUFSIZ = 1024 8 | ADDR = (HOST, PORT) 9 | 10 | tcpCliSock = socket(AF_INET, SOCK_STREAM) 11 | tcpCliSock.connect(ADDR) 12 | 13 | while True: 14 | data = raw_input('> ') 15 | if not data: 16 | break 17 | tcpCliSock.send(data) 18 | data = tcpCliSock.recv(BUFSIZ) 19 | if not data: 20 | break 21 | print data 22 | 23 | tcpCliSock.close() 24 | -------------------------------------------------------------------------------- /ch06/uniFile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | An example of reading and writing Unicode strings: Writes 4 | a Unicode string to a file in utf-8 and reads it back in. 5 | ''' 6 | CODEC = 'utf-8' 7 | FILE = 'unicode.txt' 8 | 9 | hello_out = u"Hello world\n" 10 | bytes_out = hello_out.encode(CODEC) 11 | f = open(FILE, "w") 12 | f.write(bytes_out) 13 | f.close() 14 | 15 | f = open(FILE, "r") 16 | bytes_in = f.read() 17 | f.close() 18 | hello_in = bytes_in.decode(CODEC) 19 | print hello_in, 20 | -------------------------------------------------------------------------------- /ch18/onethr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from time import sleep, ctime 4 | 5 | def loop0(): 6 | print 'start loop 0 at:', ctime() 7 | sleep(4) 8 | print 'loop 0 done at:', ctime() 9 | 10 | def loop1(): 11 | print 'start loop 1 at:', ctime() 12 | sleep(2) 13 | print 'loop 1 done at:', ctime() 14 | 15 | def main(): 16 | print 'starting at:', ctime() 17 | loop0() 18 | loop1() 19 | print 'all DONE at:', ctime() 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /ch16/alt/tsTclntNew.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from socket import * 4 | 5 | HOST = 'localhost' 6 | PORT = 21567 7 | BUFSIZ = 1024 8 | ADDR = (HOST, PORT) 9 | 10 | tcpCliSock = socket(AF_INET, SOCK_STREAM) 11 | tcpCliSock.connect(ADDR) 12 | 13 | while True: 14 | data = raw_input('> ') 15 | if not data: 16 | break 17 | tcpCliSock.send(data) 18 | print " ... waiting for reply ..." 19 | data = tcpCliSock.recv(BUFSIZ) 20 | if not data: 21 | break 22 | print data 23 | 24 | tcpCliSock.close() 25 | -------------------------------------------------------------------------------- /ch16/tsTclntSS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from socket import * 4 | 5 | HOST = 'localhost' 6 | PORT = 21567 7 | BUFSIZ = 1024 8 | ADDR = (HOST, PORT) 9 | 10 | while True: 11 | tcpCliSock = socket(AF_INET, SOCK_STREAM) 12 | tcpCliSock.connect(ADDR) 13 | data = raw_input('> ') 14 | if not data: 15 | break 16 | tcpCliSock.send('%s\r\n' % data) 17 | data = tcpCliSock.recv(BUFSIZ) 18 | if not data: 19 | break 20 | print data.strip() 21 | tcpCliSock.close() 22 | -------------------------------------------------------------------------------- /ch16/tsUserv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from socket import * 4 | from time import ctime 5 | 6 | HOST = '' 7 | PORT = 21567 8 | BUFSIZ = 1024 9 | ADDR = (HOST, PORT) 10 | 11 | udpSerSock = socket(AF_INET, SOCK_DGRAM) 12 | udpSerSock.bind(ADDR) 13 | 14 | while True: 15 | print 'waiting for message...' 16 | data, addr = udpSerSock.recvfrom(BUFSIZ) 17 | udpSerSock.sendto('[%s] %s' % ( 18 | ctime(), data), addr) 19 | print '...received from and returned to:', addr 20 | 21 | udpSerSock.close() 22 | -------------------------------------------------------------------------------- /ch16/tsTservSS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from SocketServer import (TCPServer as TCP, 4 | StreamRequestHandler as SRH) 5 | from time import ctime 6 | 7 | HOST = '' 8 | PORT = 21567 9 | ADDR = (HOST, PORT) 10 | 11 | class MyRequestHandler(SRH): 12 | def handle(self): 13 | print '...connected from:', self.client_address 14 | self.wfile.write('[%s] %s' % (ctime(), 15 | self.rfile.readline())) 16 | 17 | tcpServ = TCP(ADDR, MyRequestHandler) 18 | print 'waiting for connection...' 19 | tcpServ.serve_forever() 20 | -------------------------------------------------------------------------------- /ch23/swhello.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env jython 2 | 3 | from pawt import swing 4 | import sys 5 | from java.awt import Color, BorderLayout 6 | 7 | def quit(e): 8 | sys.exit() 9 | 10 | top = swing.JFrame("PySwing") 11 | box = swing.JPanel(BorderLayout()) 12 | hello = swing.JLabel("Hello World!") 13 | quit = swing.JButton("QUIT", actionPerformed=quit, 14 | background=Color.red, foreground=Color.white) 15 | 16 | box.add("North", hello) 17 | box.add("South", quit) 18 | top.contentPane.add(box) 19 | top.pack() 20 | top.visible = 1 # or True for Jython 2.2+ 21 | -------------------------------------------------------------------------------- /ch13/hotel.py: -------------------------------------------------------------------------------- 1 | class HotelRoomCalc: 2 | 'Hotel room rate calculator' 3 | 4 | def __init__(self, rt, sales=0.085, rm=0.1): 5 | '''HotelRoolCalc default arguments: 6 | sales tax == 8.5% and room tax == 10%''' 7 | self.salesTax = sales 8 | self.roomTax = rm 9 | self.roomRate = rt 10 | 11 | def calcTotal(self, days=1): 12 | 'Calculate total; default to daily rate' 13 | daily = round((self.roomRate * \ 14 | (1 + self.roomTax + self.salesTax)), 2) 15 | return float(days) * daily 16 | -------------------------------------------------------------------------------- /ch19/alt/tkhello2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # $Id: tkhello2.py,v 1.1 2000/02/21 09:04:25 wesc Exp $ 3 | # 4 | # tkhello2.py -- "Hello World!" 2 in Tkinter: 5 | # - "Hello World!" with just a button (which quits the app) 6 | # 7 | # created by wesc 00/02/20 8 | # 9 | 10 | # import Tkinter module 11 | import Tkinter 12 | 13 | # create toplevel window 14 | top = Tkinter.Tk() 15 | 16 | # create button 17 | quit = Tkinter.Button(top, text='Hello World!', command=top.quit) 18 | 19 | # pack button 20 | quit.pack() 21 | 22 | # enter main loop 23 | Tkinter.mainloop() 24 | -------------------------------------------------------------------------------- /ch16/alt/tsTservSS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from SocketServer import (TCPServer as TCP, 4 | StreamRequestHandler as SRH) 5 | from time import ctime 6 | 7 | HOST = '' 8 | PORT = 21567 9 | ADDR = (HOST, PORT) 10 | 11 | class MyRequestHandler(SRH): 12 | def handle(self): 13 | print '...connected from:', self.client_address 14 | self.wfile.write('[%s] %s' % (ctime(), 15 | self.rfile.readline())) 16 | 17 | tcpServ = TCP(ADDR, MyRequestHandler) 18 | tcpServ.allow_reuse_address = True 19 | print 'waiting for connection...' 20 | tcpServ.serve_forever() 21 | -------------------------------------------------------------------------------- /ch16/alt/tsTservSSBRH.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from SocketServer import BaseRequestHandler as BRH, TCPServer as TCP 4 | from time import ctime 5 | 6 | HOST = '' 7 | PORT = 21567 8 | BUFSIZ = 1024 9 | ADDR = (HOST, PORT) 10 | 11 | class MyRequestHandler(BRH): 12 | def handle(self): 13 | print '...connected from:', self.client_address 14 | self.request.send('[%s] %s' % (ctime(), 15 | self.request.recv(BUFSIZ))) 16 | 17 | tcpServ = TCP(ADDR, MyRequestHandler) 18 | tcpServ.allow_reuse_address = True 19 | print 'waiting for connection...' 20 | tcpServ.serve_forever() 21 | -------------------------------------------------------------------------------- /ch15/alt/rewho.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from os import popen # import os.popen() 4 | from re import split # import re.split() [not string.split()] 5 | from string import strip # import string.strip() 6 | 7 | f = popen('who', 'r') # call the 'who' cmd and read from it 8 | 9 | # read all output from 'who' and strip the leading & trailing whitespaces 10 | for eachLine in map(strip, f.readlines()): 11 | print split('\s\s+|\t', eachLine) # split on TAB or multiple SPACEs 12 | f.close() # close input channel 13 | -------------------------------------------------------------------------------- /ch18/myThread.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import threading 4 | from time import time, ctime 5 | 6 | class MyThread(threading.Thread): 7 | def __init__(self, func, args, name=''): 8 | threading.Thread.__init__(self) 9 | self.name = name 10 | self.func = func 11 | self.args = args 12 | 13 | def getResult(self): 14 | return self.res 15 | 16 | def run(self): 17 | print 'starting', self.name, 'at:', \ 18 | ctime() 19 | self.res = apply(self.func, self.args) 20 | print self.name, 'finished at:', \ 21 | ctime() 22 | -------------------------------------------------------------------------------- /ch06/alt/insertVsColonZero.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from time import time 4 | REPS = 17500 5 | 6 | def insert(): 7 | m = [None] 8 | i = 0 9 | now = time() 10 | while i < REPS: 11 | m.insert(0, i) 12 | i += 1 13 | print 'Elapsed (insert):', time() - now 14 | 15 | def colonZero(): 16 | m = [None] 17 | i = 0 18 | now = time() 19 | while i < REPS: 20 | m[:0] = [i] 21 | i += 1 22 | print 'Elapsed (colon-0):', time() - now 23 | 24 | def main(): 25 | insert() 26 | colonZero() 27 | 28 | if __name__ == '__main__': 29 | main() 30 | raw_input() 31 | -------------------------------------------------------------------------------- /ch13/anyIter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class AnyIter(object): 4 | def __init__(self, data, safe=0): 5 | self.safe = safe 6 | self.iter = iter(data) 7 | 8 | def __iter__(self): 9 | return self 10 | 11 | def next(self, howmany=1): 12 | retval = [] 13 | for eachItem in range(howmany): 14 | try: 15 | retval.append(self.iter.next()) 16 | except StopIteration: 17 | if self.safe: 18 | break 19 | else: 20 | raise 21 | return retval 22 | -------------------------------------------------------------------------------- /ch18/mtsleep1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import thread 4 | from time import sleep, ctime 5 | 6 | def loop0(): 7 | print 'start loop 0 at:', ctime() 8 | sleep(4) 9 | print 'loop 0 done at:', ctime() 10 | 11 | def loop1(): 12 | print 'start loop 1 at:', ctime() 13 | sleep(2) 14 | print 'loop 1 done at:', ctime() 15 | 16 | def main(): 17 | print 'starting at:', ctime() 18 | thread.start_new_thread(loop0, ()) 19 | thread.start_new_thread(loop1, ()) 20 | sleep(6) 21 | print 'all DONE at:', ctime() 22 | 23 | if __name__ == '__main__': 24 | main() 25 | -------------------------------------------------------------------------------- /ch16/tsTservTW.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from twisted.internet import protocol, reactor 4 | from time import ctime 5 | 6 | PORT = 21567 7 | 8 | class TSServProtocol(protocol.Protocol): 9 | def connectionMade(self): 10 | clnt = self.clnt = self.transport.getPeer().host 11 | print '...connected from:', clnt 12 | def dataReceived(self, data): 13 | self.transport.write('[%s] %s' % ( 14 | ctime(), data)) 15 | 16 | factory = protocol.Factory() 17 | factory.protocol = TSServProtocol 18 | print 'waiting for connection...' 19 | reactor.listenTCP(PORT, factory) 20 | reactor.run() 21 | -------------------------------------------------------------------------------- /ch20/friends.htm: -------------------------------------------------------------------------------- 1 |
15 | You have %s friends.
16 | '''
17 |
18 | # process() does all the work
19 | def process():
20 |
21 | # initialize Data class object
22 | form = cgi.FieldStorage()
23 |
24 | # get name and number of friends
25 | who = form['person'].value
26 | howmany = form['howmany'].value
27 |
28 | # substitute in real name and number of friends and return
29 | print reshtml % (who, who, howmany)
30 |
31 | # invoke if called directly
32 | if __name__ == '__main__':
33 | process()
34 |
--------------------------------------------------------------------------------
/ch20/urlopenAuth.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import urllib2
4 |
5 | LOGIN = 'wesley'
6 | PASSWD = "you'llNeverGuess"
7 | URL = 'http://localhost'
8 |
9 | def handler_version(url):
10 | from urlparse import urlparse as up
11 | hdlr = urllib2.HTTPBasicAuthHandler()
12 | hdlr.add_password('Archives', up(url)[1], LOGIN, PASSWD)
13 | opener = urllib2.build_opener(hdlr)
14 | urllib2.install_opener(opener)
15 | return url
16 |
17 | def request_version(url):
18 | from base64 import encodestring
19 | req = urllib2.Request(url)
20 | b64str = encodestring('%s:%s' % (LOGIN, PASSWD))[:-1]
21 | req.add_header("Authorization", "Basic %s" % b64str)
22 | return req
23 |
24 | for funcType in ('handler', 'request'):
25 | print '*** Using %s:' % funcType.upper()
26 | url = eval('%s_version')(URL)
27 | f = urllib2.urlopen(url)
28 | print f.readline()
29 | f.close()
30 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | lib/
17 | lib64/
18 | parts/
19 | sdist/
20 | var/
21 | *.egg-info/
22 | .installed.cfg
23 | *.egg
24 |
25 | # PyInstaller
26 | # Usually these files are written by a python script from a template
27 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
28 | *.manifest
29 | *.spec
30 |
31 | # Installer logs
32 | pip-log.txt
33 | pip-delete-this-directory.txt
34 |
35 | # Unit test / coverage reports
36 | htmlcov/
37 | .tox/
38 | .coverage
39 | .cache
40 | nosetests.xml
41 | coverage.xml
42 |
43 | # Translations
44 | *.mo
45 | *.pot
46 |
47 | # Django stuff:
48 | *.log
49 |
50 | # Sphinx documentation
51 | docs/_build/
52 |
53 | # PyBuilder
54 | target/
55 |
--------------------------------------------------------------------------------
/ch13/descrPRE25.diff:
--------------------------------------------------------------------------------
1 | --- descr.py 2006-04-10 17:42:53.000000000 -0700
2 | +++ descrPRE25.py 2006-10-11 22:26:43.000000000 -0700
3 | @@ -6,7 +6,7 @@
4 | class FileDescr(object):
5 | saved = []
6 |
7 | - def __init__(self, name=None):
8 | + def __init__(self, name):
9 | self.name = name
10 |
11 | def __get__(self, obj, typ=None):
12 | @@ -26,12 +26,12 @@
13 | "could not read %r: %s" % self.name
14 |
15 | def __set__(self, obj, val):
16 | - f = open(self.name, 'w')
17 | try:
18 | try:
19 | + f = open(self.name, 'w')
20 | pickle.dump(val, f)
21 | FileDescr.saved.append(self.name)
22 | - except (TypeError, pickle.PicklingError), e:
23 | + except (IOError, TypeError, pickle.PicklingError), e:
24 | raise AttributeError, \
25 | "could not pickle %r" % self.name
26 | finally:
27 |
--------------------------------------------------------------------------------
/ch17/myMail.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from smtplib import SMTP
4 | from poplib import POP3
5 | from time import sleep
6 |
7 | SMTPSVR = 'smtp.python.is.cool'
8 | POP3SVR = 'pop.python.is.cool'
9 |
10 | origHdrs = ['From: wesley@python.is.cool',
11 | 'To: wesley@python.is.cool',
12 | 'Subject: test msg']
13 | origBody = ['xxx', 'yyy', 'zzz']
14 | origMsg = '\r\n\r\n'.join(['\r\n'.join(origHdrs), '\r\n'.join(origBody)])
15 |
16 | sendSvr = SMTP(SMTPSVR)
17 | errs = sendSvr.sendmail('wesley@python.is.cool',
18 | ('wesley@python.is.cool', ), origMsg)
19 | sendSvr.quit()
20 | assert len(errs) == 0, errs
21 | sleep(10) # wait for mail to be delivered
22 |
23 | recvSvr = POP3(POP3SVR)
24 | recvSvr.user('wesley')
25 | recvSvr.pass_('youllNeverGuess')
26 | rsp, msg, siz = recvSvr.retr(recvSvr.stat()[0])
27 | # strip headers and compare to orig msg
28 | sep = msg.index('')
29 | recvBody = msg[sep+1:]
30 | assert origBody == recvBody # assert identical
31 |
--------------------------------------------------------------------------------
/ch11/closureVars.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | output = '
35 | You have %s friends.
36 | '''
37 |
38 | def doResults(who, howmany):
39 | print header + reshtml % (who, who, howmany)
40 |
41 | def process():
42 | form = cgi.FieldStorage()
43 | if form.has_key('person'):
44 | who = form['person'].value
45 | else:
46 | who = 'NEW USER'
47 |
48 | if form.has_key('howmany'):
49 | howmany = form['howmany'].value
50 | else:
51 | howmany = 0
52 |
53 | if form.has_key('action'):
54 | doResults(who, howmany)
55 | else:
56 | showForm()
57 |
58 | if __name__ == '__main__':
59 | process()
60 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Core-Python-Programming-2nd-Edition-Examples-and-Source-Code
2 | ============================================================
3 |
4 | Examples and source code from the book "Core Python Programming", 2nd Edition, by Wesley J. Chun
5 |
6 | These directories contain all of the source code for the
7 | applications in the book, e.g., Example x.y, with each
8 | directory representing the code for a chapter in the book
9 | which features at least one code Example.
10 |
11 | In each directory, you may also find a subdirectory named
12 | "alt" which will contain alternative source code. These
13 | can include:
14 |
15 | - Applications that have been more fully-commented
16 | - Some of the more lengthy code snippets featured as
17 | chapter reading
18 | - Modified applications which run on older (or newer)
19 | versions of Python
20 |
21 | ----
22 |
23 | **License**
24 |
25 | Source code for the book is released under the
26 | Creative Commons Attribution-SharedAlike2.5 License.
27 | This means that you are free to:
28 |
29 | * copy, distribute, display, and perform the work
30 | * make derivative works
31 | * make commercial use of the work
32 |
33 | ...under the following conditions:
34 |
35 | * Attribution: You must attribute the work in this
36 | manner specified by the author or licensor... state
37 | the following in copies or derivations of the work:
38 |
39 | "(c) 2007 CyberWeb Consulting and Pearson Education.
40 | All Rights Reserved."
41 |
42 | * Share Alike. If you alter, transform, or build
43 | upon this work, you may distribute the resulting
44 | work only under a license identical to this one.
45 |
46 | For more information, see:
47 | http://creativecommons.org/licenses/by-sa/2.5/
--------------------------------------------------------------------------------
/ch15/alt/gendata.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # $Id$
3 | #
4 | # gendata.py -- generates test data
5 | #
6 | # created on 00/05/19 by wesc
7 | #
8 |
9 | from random import randint, choice
10 | from time import ctime
11 | from sys import maxint # (value, not function)
12 | from string import lowercase
13 | from os.path import exists
14 |
15 | doms = ( 'com', 'edu', 'net', 'org', 'gov' )
16 |
17 | def main():
18 |
19 | # this long version saves output to files which
20 | # can be directly used with regular expressions
21 | # (it does not write the strings to the screen)
22 |
23 | # open new test file
24 | i = 0
25 | fn = '/tmp/data%d.txt' % i
26 | while exists(fn):
27 | i = i + 1
28 | fn = '/tmp/data%d.txt' % i
29 | f = open(fn, 'w')
30 |
31 | # write test data and close file
32 | for i in range(randint(5, 10)):
33 |
34 | # randomly choose a date integer and
35 | # calculate the corresponding date string
36 | dtint = randint(0, maxint-1)
37 | dtstr = ctime(dtint)
38 |
39 | # the login should be between 4 and 7 chars in length;
40 | # the domain should be
41 | loginlen = randint(4, 7)
42 | login = ''
43 | for j in range(loginlen):
44 | login = login + choice(lowercase)
45 |
46 | domainlen = randint(loginlen, 12)
47 | dom = ''
48 | for j in range(domainlen):
49 | dom = dom + choice(lowercase)
50 | f.write('%s:%s@%s.%s:%d-%d-%d\n' % (dtstr, login,
51 | dom, choice(doms), dtint, loginlen, domainlen))
52 |
53 | # close test file
54 | f.close()
55 |
56 | if __name__ == '__main__':
57 | main()
58 |
--------------------------------------------------------------------------------
/ch14/loopmake.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | dashes = '\n' + '-' * 50
4 | exec_dict = {
5 |
6 | 'f': """ # for loop
7 | for %s in %s:
8 | print %s
9 | """,
10 |
11 | 's': """ # sequence while loop
12 | %s = 0
13 | %s = %s
14 | while %s < len(%s):
15 | print %s[%s]
16 | %s = %s + 1
17 | """,
18 |
19 | 'n': """ # counting while loop
20 | %s = %d
21 | while %s < %d:
22 | print %s
23 | %s = %s + %d
24 | """
25 | }
26 |
27 | def main():
28 |
29 | ltype = raw_input('Loop type? (For/While) ')
30 | dtype = raw_input('Data type? (Number/Sequence) ')
31 |
32 | if dtype == 'n':
33 | start = input('Starting value? ')
34 | stop = input('Ending value (non-inclusive)? ')
35 | step = input('Stepping value? ')
36 | seq = str(range(start, stop, step))
37 |
38 | else:
39 | seq = raw_input('Enter sequence: ')
40 |
41 | var = raw_input('Iterative variable name? ')
42 |
43 | if ltype == 'f':
44 | exec_str = exec_dict['f'] % (var, seq, var)
45 |
46 | elif ltype == 'w':
47 | if dtype == 's':
48 | svar = raw_input('Enter sequence name? ')
49 | exec_str = exec_dict['s'] % \
50 | (var, svar, seq, var, svar, svar, var, var, var)
51 |
52 | elif dtype == 'n':
53 | exec_str = exec_dict['n'] % \
54 | (var, start, var, stop, var, var, var, step)
55 |
56 | print dashes
57 | print 'The custom-generated code for you is:' + dashes
58 | print exec_str + dashes
59 | print 'Test execution of the code:' + dashes
60 | exec exec_str
61 | print dashes
62 |
63 | if __name__ == '__main__':
64 | main()
65 |
--------------------------------------------------------------------------------
/ch13/alt/twrapme.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # $Id: twrapme.py,v 1.1 2000/06/02 08:14:55 wesc Exp $
3 | #
4 | # twrapme.py -- another simple wrapping example
5 | #
6 | # created on 00/04/26 by wesc
7 | #
8 |
9 | from time import time, ctime # import time.time(), time.ctime()
10 |
11 | class TimedWrapMe:
12 |
13 | # constructor, sets data item to wrap and
14 | # updates create, modify, and access times
15 | def __init__(self, obj):
16 | self.__data = obj
17 | self.__ctime = self.__mtime = self.__atime = time()
18 |
19 | # sets new data value, updates modify and access times
20 | def set(self, obj):
21 | self.__data = obj
22 | self.__mtime = self.__atime = time()
23 |
24 | # gets current data value, updates access time
25 | def get(self):
26 | self.__atime = time()
27 | return self.__data
28 |
29 | # get request time value
30 | def gettimeval(self, t_type):
31 | if type(t_type) != type('') or t_type[0] not in 'cma':
32 | raise TypeError, "gettime() requires argument of 'c', 'm', or 'a'"
33 | return eval('self._%s__%stime' % (self.__class__.__name__, t_type[0]))
34 |
35 | # get request time string
36 | def gettimestr(self, t_type):
37 | return ctime(self.gettimeval(t_type))
38 |
39 | # repr() and `` call this
40 | def __repr__(self):
41 | self.__atime = time()
42 | return `self.__data`
43 |
44 | # str() calls this
45 | def __str__(self):
46 | self.__atime = time()
47 | return str(self.__data)
48 |
49 | # delegate all other functionality to object's native methods
50 | def __getattr__(self, attr):
51 | self.__atime = time()
52 | return getattr(self.__data, attr)
53 |
--------------------------------------------------------------------------------
/ch09/ospathex.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | for tmpdir in ('/tmp', 'c:/windows/temp'):
5 | if os.path.isdir(tmpdir):
6 | break
7 | else:
8 | print 'no temp directory available'
9 | tmpdir = ''
10 |
11 | if tmpdir:
12 | os.chdir(tmpdir)
13 | cwd = os.getcwd()
14 | print '*** current temporary directory'
15 | print cwd
16 |
17 | print '*** creating example directory...'
18 | os.mkdir('example')
19 | os.chdir('example')
20 | cwd = os.getcwd()
21 | print '*** new working directory:'
22 | print cwd
23 | print '*** original directory listing:'
24 | print os.listdir(cwd)
25 |
26 | print '*** creating test file...'
27 | file = open('test', 'w')
28 | file.write('foo\n')
29 | file.write('bar\n')
30 | file.close()
31 | print '*** updated directory listing:'
32 | print os.listdir(cwd)
33 |
34 | print "*** renaming 'test' to 'filetest.txt'"
35 | os.rename('test', 'filetest.txt')
36 | print '*** updated directory listing:'
37 | print os.listdir(cwd)
38 |
39 | path = os.path.join(cwd, os.listdir(cwd)[0])
40 | print '*** full file pathname:'
41 | print path
42 | print '*** (pathname, basename) == '
43 | print os.path.split(path)
44 | print '*** (filename, extension) == '
45 | print os.path.splitext(os.path.basename(path))
46 |
47 | print '*** displaying file contents:'
48 | file = open(path)
49 | allLines = file.readlines()
50 | file.close()
51 | for eachLine in allLines:
52 | print eachLine,
53 |
54 | print '*** deleting test file'
55 | os.remove(path)
56 | print '*** updated directory listing:'
57 | print os.listdir(cwd)
58 | os.chdir(os.pardir)
59 | print '*** deleting test directory'
60 | os.rmdir('example')
61 | print '*** DONE'
62 |
--------------------------------------------------------------------------------
/ch13/alt/descr.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | import pickle
5 |
6 | class FileDescr(object):
7 | '''
8 | FileDescr -- description which uses the file
9 | system to archive instance attributes
10 | '''
11 | saved = []
12 |
13 | def __init__(self, name):
14 | '__init__() -- saves the attribute name'
15 | self.name = name
16 |
17 | def __get__(self, obj, typ=None):
18 | '__get__() -- retrives attribute from disk'
19 | self.name = name
20 | if self.name not in FileDescr.saved:
21 | raise AttributeError, \
22 | "%r used before assignment" % self.name
23 |
24 | # open pickle file and load object; choke on failure
25 | try:
26 | f = open(self.name, 'r')
27 | val = pickle.load(f)
28 | f.close()
29 | return val
30 | except (pickle.UnpicklingError, IOError,
31 | EOFError, AttributeError,
32 | ImportError, IndexError), e:
33 | raise AttributeError, \
34 | "could not read %r: %s" % self.name
35 |
36 | def __set__(self, obj, val):
37 | '__set__() -- saves attribute to disk'
38 | try:
39 | try:
40 | f = open(self.name, 'w')
41 | pickle.dump(val, f)
42 | FileDescr.saved.append(self.name)
43 | except (IOError, TypeError, pickle.PicklingError), e:
44 | raise AttributeError, \
45 | "could not pickle %r" % self.name
46 | finally:
47 | f.close()
48 |
49 | def __delete__(self, obj):
50 | '__set__() -- removes instance attribute'
51 | try:
52 | os.unlink(self.name)
53 | FileDescr.saved.remove(self.name)
54 | except (OSError, ValueError), e:
55 | pass
56 |
--------------------------------------------------------------------------------
/ch11/alt/deco.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from time import ctime, sleep
4 |
5 | '''
6 | def counter(func):
7 | if not hasattr(func, 'ncalls'):
8 | print '*** initializing ctr'
9 | func.ncalls = [0]
10 | def wrappedFunc():
11 | func.ncalls[0] += 1
12 | print '*** incrementing ctr to', func.ncalls
13 | print 'INSIDE: id(func) =', id(func)
14 | return func()
15 | print 'id(func) =', id(func)
16 | print 'id(wrappedfunc) =', id(wrappedFunc)
17 | wrappedFunc.ncalls = func.ncalls
18 | return wrappedFunc
19 | '''
20 |
21 | def tsfunc(func):
22 | def wrappedFunc():
23 | print '[%s] %s() called' % (
24 | ctime(), func.__name__)
25 | return func()
26 | return wrappedFunc
27 |
28 | @tsfunc
29 | def foo():
30 | pass
31 |
32 | foo()
33 | sleep(4)
34 |
35 | for i in range(2):
36 | sleep(1)
37 | foo()
38 |
39 | '''
40 | #exer
41 | update example XXX to:
42 | - write the timestamp to a logfile instead of screen output
43 | - time how long it takes to exec the given function, i.e., see the timeit() exercise above
44 | - create a function registry:
45 | track the number of functions which have registered with your system,
46 | how many times those functions have been called,
47 | and what are the avg time of each execution and total time of execution
48 |
49 | - write a memoizer... for small recursive functions or just for simple functions that are called a lot, cache the results given a set of arguments (must be hashable, i.e, immutable objects), so that if the same function is called again with the same args, then just return the previously saved value instead of (re)running the function from scratch. There are many examples online (use a search engine), so that even if you are inspired by an existing piece of code, customize that code by making an improvement that is truly your own.
50 |
51 | '''
52 |
--------------------------------------------------------------------------------
/ch13/alt/moneyfmt.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # $Id: moneyfmt.py,v 1.2 2000/02/07 07:46:09 wesc Exp $
3 | #
4 | # moneyfmt.py -- create a class that prints a floating-point
5 | # value in a financial format
6 | #
7 | # created 00/02/07 by wesc
8 | #
9 |
10 | """Implements the Dollar class for displaying a financial
11 | format for single floating-point values. Also see
12 | moneyfmt.MoneyFmt.__doc__.
13 | """
14 |
15 | class MoneyFmt(object):
16 |
17 | """This class...
18 |
19 | x = dollar.Dollar(amount) # amount is a float
20 |
21 | NOTE: str() will give the formatted display while repr() and `` will
22 | give the raw float value. This allows for both pretty-printing
23 | output as well as the ability to still manipulate the values.
24 |
25 | Methods:
26 |
27 | x.update([amount]) -- updates the value of the number
28 | """
29 |
30 | def __init__(self, value=0.): # constructor
31 |
32 | self.value = float(value)
33 |
34 |
35 | def update(self, value=None): # allow updates
36 |
37 | """x.update([amount])
38 | You can update the amount with this method.
39 | If the value is missing, the value is not updated.
40 | Also see moneyfmt.MoneyFmt.__doc__.
41 | """
42 |
43 | ###
44 | ### (a) FILL THIS IN
45 | ###
46 |
47 |
48 | def __nonzero__(self): # boolean test (same as float)
49 |
50 | return int(self.value)
51 |
52 |
53 | def __repr__(self): # standalone, as a float number
54 |
55 | return str(self.value)
56 |
57 |
58 | def __str__(self): # display in requested format
59 |
60 | val = ''
61 |
62 | ###
63 | ### (b) FILL THIS IN... don't forget about negative numbers too!!
64 | ###
65 |
66 | return val
67 |
--------------------------------------------------------------------------------
/ch22/Extest2.c:
--------------------------------------------------------------------------------
1 | #include
37 | You have %s friends.
38 | '''
39 |
40 | def doResults(who, howmany):
41 | # substitute in real name and number of friends and return
42 | print header + reshtml % (who, who, howmany)
43 |
44 |
45 | # process() does all the work
46 | def process():
47 |
48 | # initialize Data class object
49 | form = cgi.FieldStorage()
50 |
51 | # get user name
52 | if form.has_key('person'):
53 | who = form['person'].value
54 | else:
55 | who = 'NEW USER'
56 |
57 | # get name and number of friends
58 | if form.has_key('howmany'):
59 | howmany = form['howmany'].value
60 | else:
61 | howmany = 0
62 |
63 | # if editing, show results
64 | if form.has_key('action'):
65 | doResults(who, howmany)
66 |
67 | # otherwise, show form
68 | else:
69 | showForm()
70 |
71 | # invoke if called directly
72 | if __name__ == '__main__':
73 | process()
74 |
--------------------------------------------------------------------------------
/ch10/alt/cardrun.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | $Id$
4 |
5 | cardrun.py -- "credit card run" script serves as a demo for a
6 | ficticious credit card transaction processing application
7 | which reads data in from a file and uses the safe_float()
8 | function along with try-except to safely "ignore bad data"
9 | such as string text as opposed to strictly numerical input.
10 | '''
11 |
12 | # safe_float() --> float
13 | def safe_float(object):
14 | 'safe_float() converts strings to floats "safely"'
15 |
16 | # attempt to convert object using float()
17 | try:
18 | retval = float(object)
19 |
20 | # failure return value is error reason
21 | except (TypeError, ValueError), e:
22 | retval = str(e)
23 |
24 | return retval
25 |
26 |
27 | # main() --> None
28 | def main():
29 | 'main() handles all the data processing'
30 |
31 | # attempt to open data file
32 | try:
33 | ccfile = open('carddata.txt', 'r')
34 |
35 | # display error reason on failure
36 | except IOError, e:
37 | print 'file open failed:', e
38 | return
39 |
40 | # otherwise show a diagnostic 'ok'
41 | else:
42 | print 'file opened successfully'
43 |
44 | # read all data and close file
45 | txns = ccfile.readlines()
46 | ccfile.close()
47 |
48 | # processing setup
49 | total = 0.00
50 | print 'processing new account, log:'
51 |
52 | # look at each transaction
53 | for eachTxn in txns:
54 | result = safe_float(eachTxn)
55 |
56 | # string indicates failure ...
57 | if isinstance(result, basestring):
58 | if eachTxn[0] == '#':
59 | print 'comment... ignored'
60 | else:
61 | print '\ncategory:', eachTxn
62 |
63 | # ... while float means success
64 | elif isinstance(result, float):
65 | total += result
66 | print 'processing transaction of: %.2f' % result
67 |
68 | # unknown return type from safe_float()
69 | else:
70 | print 'invalid return type from safe_float()... ignored'
71 |
72 | # display final totals
73 | print 'new balance: $%.2f' % (total)
74 |
75 | # call main() if invoked as script
76 | if __name__ == '__main__':
77 | main()
78 |
--------------------------------------------------------------------------------
/ch06/alt/stack.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | $Id$
4 |
5 | stack.py -- simulate stack data structures using lists
6 |
7 | Exercises:
8 |
9 | 13-8) create a Stack class
10 |
11 | 13-10) create a class similar to arrays in Perl which have
12 | both queue- and stack-like qualities and features
13 | '''
14 |
15 | # create our data structure
16 | stack = []
17 |
18 | #
19 | # pushit() -- adds stirng to the stack
20 | #
21 | def pushit():
22 | stack.append(raw_input('Enter new string: '))
23 |
24 | #
25 | # popit() -- removes stirng from the stack
26 | #
27 | def popit():
28 | if len(stack) == 0:
29 | print 'Cannot pop from an empty stack!'
30 | else:
31 | print 'Removed [', stack.pop(), ']'
32 |
33 | #
34 | # viewstack() -- display stack contents
35 | #
36 | def viewstack():
37 | print str(stack)
38 |
39 | #
40 | # showmenu() -- interactive portion of application
41 | # displays menu to prompt user and takes
42 | # action based on user response
43 | #
44 | def showmenu():
45 |
46 | # using triple quotes to help us put together
47 | # the multi-line string prompt to display
48 | prompt = """
49 | p(U)sh
50 | p(O)p
51 | (V)iew
52 | (Q)uit
53 |
54 | Enter choice: """
55 |
56 | # loop until user quits
57 | done = 0
58 | while not done:
59 |
60 | # loop until user choses valid option
61 | chosen = 0
62 | while not chosen:
63 |
64 | # if user hits RETURN/Enter, ^C, or ^D (EOF),
65 | # pretend they typed 'q' to quit normally
66 | try:
67 | choice = raw_input(prompt)[0]
68 | except (IndexError, EOFError, KeyboardInterrupt):
69 | choice = 'q'
70 | print '\nYou picked: [%s]' % choice
71 |
72 | # validate option chosen
73 | if choice not in 'uovq':
74 | print 'invalid option, try again'
75 | else:
76 | chosen = 1
77 |
78 | # take appropriate action
79 | if choice == 'q':
80 | done = 1
81 | if choice == 'u':
82 | pushit()
83 | if choice == 'o':
84 | popit()
85 | if choice == 'v':
86 | viewstack()
87 |
88 | # run showmenu() as the application
89 | if __name__ == '__main__':
90 | showmenu()
91 |
--------------------------------------------------------------------------------
/ch06/alt/queue.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | $Id$
4 |
5 | queue.py -- simulate queue data structures using lists
6 |
7 | NOTE: as of the time of publication, there is a bug in JPython1.1
8 | that does not recognize arguments for the list pop() method:
9 | TypeError: pop(): expected 0 args; got 1
10 |
11 | Exercises:
12 |
13 | 13-9) create a Queue class
14 |
15 | 13-10) create a class similar to arrays in Perl which have
16 | both queue- and stack-like qualities and features
17 | '''
18 |
19 | # create our data structure
20 | queue = []
21 |
22 | #
23 | # enQ() -- add string to end of queue
24 | #
25 | def enQ():
26 | queue.append(raw_input('Enter new queue element: '))
27 |
28 | #
29 | # deQ() -- remove string from front of queue
30 | #
31 | def deQ():
32 | if len(queue) == 0:
33 | print 'Cannot dequeue from empty queue!'
34 | else:
35 | print 'Removed [', queue.pop(0), ']'
36 |
37 | #
38 | # viewQ() -- display queue contents
39 | #
40 | def viewQ():
41 | print str(queue)
42 |
43 | #
44 | # showmenu() -- interactive portion of application
45 | # displays menu to prompt user and takes
46 | # action based on user response
47 | #
48 | def showmenu():
49 | prompt = """
50 | (E)nqueue
51 | (D)equeue
52 | (V)iew
53 | (Q)uit
54 |
55 | Enter choice: """
56 |
57 | # loop until user quits
58 | done = 0
59 | while not done:
60 |
61 | # loop until user choses valid option
62 | chosen = 0
63 | while not chosen:
64 |
65 | # if user hits ^C or ^D (EOF),
66 | # pretend they typed 'q' to quit
67 | try:
68 | choice = raw_input(prompt)[0]
69 | except (IndexError, EOFError, KeyboardInterrupt):
70 | choice = 'q'
71 | print '\nYou picked: [%s]' % choice
72 |
73 | # validate option chosen
74 | if choice not in 'devq':
75 | print 'invalid option, try again'
76 | else:
77 | chosen = 1
78 |
79 | # take appropriate action
80 | if choice == 'q':
81 | done = 1
82 | if choice == 'e':
83 | enQ()
84 | if choice == 'd':
85 | deQ()
86 | if choice == 'v':
87 | viewQ()
88 |
89 | # run showmenu() as the application
90 | if __name__ == '__main__':
91 | showmenu()
92 |
--------------------------------------------------------------------------------
/ch20/friends3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import cgi
4 | from urllib import quote_plus
5 | from string import capwords
6 |
7 | header = 'Content-Type: text/html\n\n'
8 | url = '/cgi-bin/friends3.py'
9 |
10 | errhtml = '''
14 |
48 | You have %s friends.
49 | Click here to edit your data again.
50 | '''
51 |
52 | def doResults(who, howmany):
53 | newurl = url + '?action=reedit&person=%s&howmany=%s' % \
54 | (quote_plus(who), howmany)
55 | print header + reshtml % (who, who, howmany, newurl)
56 |
57 | def process():
58 | error = ''
59 | form = cgi.FieldStorage()
60 |
61 | if form.has_key('person'):
62 | who = capwords(form['person'].value)
63 | else:
64 | who = 'NEW USER'
65 |
66 | if form.has_key('howmany'):
67 | howmany = form['howmany'].value
68 | else:
69 | if form.has_key('action') and \
70 | form['action'].value == 'edit':
71 | error = 'Please select number of friends.'
72 | else:
73 | howmany = 0
74 |
75 | if not error:
76 | if form.has_key('action') and \
77 | form['action'].value != 'reedit':
78 | doResults(who, howmany)
79 | else:
80 | showForm(who, howmany)
81 | else:
82 | showError(error)
83 |
84 | if __name__ == '__main__':
85 | process()
86 |
--------------------------------------------------------------------------------
/ch17/getLatestNNTP.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import nntplib
4 | import socket
5 |
6 | HOST = 'your.nntp.sersper'
7 | GRNM = 'comp.lang.python'
8 | USER = 'wesley'
9 | PASS = "you'llNeverGuess"
10 |
11 | def main():
12 |
13 | try:
14 | n = nntplib.NNTP(HOST)
15 | #user=USER, password=PASS)
16 | except socket.gaierror, e:
17 | print 'ERROR: cannot reach host "%s"' % HOST
18 | print ' ("%s")' % eval(str(e))[1]
19 | return
20 | except nntplib.NNTPPermanentError, e:
21 | print 'ERROR: access denied on "%s"' % HOST
22 | print ' ("%s")' % str(e)
23 | return
24 | print '*** Connected to host "%s"' % HOST
25 |
26 | try:
27 | rsp, ct, fst, lst, grp = n.group(GRNM)
28 | except nntplib.NNTPTemporaryError, e:
29 | print 'ERROR: cannot connect to group "%s"' % GRNM
30 | print ' ("%s")' % str(e)
31 | print ' Server may require authentication'
32 | print ' Uncomment/edit login line above'
33 | n.quit()
34 | return
35 | except nntplib.NNTPTemporaryError, e:
36 | print 'ERROR: group "%s" unavailable' % GRNM
37 | print ' ("%s")' % str(e)
38 | n.quit()
39 | return
40 | print '*** Found newsgroup "%s"' % GRNM
41 |
42 | rng = '%s-%s' % (lst, lst)
43 | rsp, frm = n.xhdr('from', rng)
44 | rsp, sub = n.xhdr('subject', rng)
45 | rsp, dat = n.xhdr('date', rng)
46 | print '''*** Found last article (#%s):
47 |
48 | From: %s
49 | Subject: %s
50 | Date: %s
51 | '''% (lst, frm[0][1], sub[0][1], dat[0][1])
52 |
53 | rsp, anum, mid, data = n.body(lst)
54 | displayFirst20(data)
55 | n.quit()
56 |
57 | def displayFirst20(data):
58 | print '*** First (<= 20) meaningful lines:\n'
59 | count = 0
60 | lines = (line.rstrip() for line in data)
61 | lastBlank = True
62 | for line in lines:
63 | if line:
64 | lower = line.lower()
65 | if (lower.startswith('>') and not \
66 | lower.startswith('>>>')) or \
67 | lower.startswith('|') or \
68 | lower.startswith('in article') or \
69 | lower.endswith('writes:') or \
70 | lower.endswith('wrote:'):
71 | continue
72 | if not lastBlank or (lastBlank and line):
73 | print ' %s' % line
74 | if line:
75 | count += 1
76 | lastBlank = False
77 | else:
78 | lastBlank = True
79 | if count == 20:
80 | break
81 |
82 | if __name__ == '__main__':
83 | main()
84 |
--------------------------------------------------------------------------------
/ch10/myexc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os, socket, errno, types, tempfile
4 |
5 | class NetworkError(IOError):
6 | pass
7 |
8 | class FileError(IOError):
9 | pass
10 |
11 | def updArgs(args, newarg=None):
12 | if isinstance(args, IOError):
13 | myargs = []
14 | myargs.extend([arg for arg in args])
15 | else:
16 | myargs = list(args)
17 |
18 | if newarg:
19 | myargs.append(newarg)
20 |
21 | return tuple(myargs)
22 |
23 | def fileArgs(fn, mode, args):
24 | if args[0] == errno.EACCES and \
25 | 'access' in dir(os):
26 | perms = ''
27 | permd = {'r': os.R_OK, 'w': os.W_OK,
28 | 'x': os.X_OK}
29 | pkeys = permd.keys()
30 | pkeys.sort()
31 | pkeys.reverse()
32 |
33 | for eachPerm in 'rwx':
34 | if os.access(fn, permd[eachPerm]):
35 | perms = perms + eachPerm
36 | else:
37 | perms = perms + '-'
38 |
39 | if isinstance(args, IOError):
40 | myargs = []
41 | myargs.extend([arg for arg in args])
42 | else:
43 | myargs = list(args)
44 |
45 | myargs[1] = "'%s' %s (perms: '%s')" % \
46 | (mode, myargs[1], perms)
47 |
48 | myargs.append(args.filename)
49 |
50 | else:
51 | myargs = args
52 |
53 | return tuple(myargs)
54 |
55 | def myconnect(sock, host, port):
56 | try:
57 | sock.connect((host, port))
58 |
59 | except socket.error, args:
60 | myargs = updArgs(args) # convert inst to tuple
61 | if len(myargs) == 1: # no #s on some errors
62 | myargs = (errno.ENXIO, myargs[0])
63 |
64 | raise NetworkError, \
65 | updArgs(myargs, host + ':' + str(port))
66 |
67 | def myopen(fn, mode='r'):
68 | try:
69 | fo = open(fn, mode)
70 | except IOError, args:
71 | raise FileError, fileArgs(fn, mode, args)
72 |
73 | return fo
74 |
75 | def testfile():
76 |
77 | fn = tempfile.mktemp()
78 | f = open(fn, 'w')
79 | f.close()
80 |
81 | for eachTest in ((0, 'r'), (0100, 'r'), \
82 | (0400, 'w'), (0500, 'w')):
83 | try:
84 | os.chmod(fn, eachTest[0])
85 | f = myopen(fn, eachTest[1])
86 |
87 | except FileError, args:
88 | print "%s: %s" % \
89 | (args.__class__.__name__, args)
90 | else:
91 | print fn, "opened ok... perms ignored"
92 | f.close()
93 |
94 | os.chmod(fn, 0777) # enable all perms
95 | os.unlink(fn)
96 |
97 | def testnet():
98 | s = socket.socket(socket.AF_INET,
99 | socket.SOCK_STREAM)
100 |
101 | for eachHost in (YOUR HOSTS HERE)
102 | try:
103 | myconnect(s, eachHost, 80)
104 | except NetworkError, args:
105 | print "%s: %s" % \
106 | (args.__class__.__name__, args)
107 |
108 | if __name__ == '__main__':
109 | testfile()
110 | testnet()
111 |
--------------------------------------------------------------------------------
/ch07/alt/userpw.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | $Id$
4 |
5 | userpw.py -- maintain a "user database" consisting of a set
6 | of login names and corresponding passwords
7 |
8 | Exercises:
9 |
10 | 7-5a) add a timestamp to the data stored so that the
11 | user is informed of last successful login
12 |
13 | 7-5b) add an "administrative user" which can remove
14 | users from the database as well as view the
15 | entire list of current users
16 |
17 | 7-5c) add a level of security by encrypting passwords
18 |
19 | 7-5d) at a GUI interface if you are familiar with one
20 | such as Tkinter
21 |
22 | 9-13a) store the data base to a disk file so that you
23 | do not have to "recreate" the database every
24 | time you run your application
25 |
26 | 9-13b) use the pickle module to store the database
27 | object directly as opposed to writing out the
28 | data one line at a time
29 | '''
30 | # clear database dictionary
31 | db = {}
32 |
33 | #
34 | # newuser() -- create new user and add to database
35 | #
36 | def newuser():
37 | prompt = 'login desired: '
38 | while 1:
39 | name = raw_input(prompt)
40 | if db.has_key(name):
41 | prompt = 'name taken, try another: '
42 | continue
43 | else:
44 | break
45 | pwd = raw_input('passwd: ')
46 | db[name] = pwd
47 |
48 |
49 | #
50 | # olduser() -- verify password to login existing users
51 | #
52 | def olduser():
53 | name = raw_input('login: ')
54 | pwd = raw_input('passwd: ')
55 | passwd = db.get(name)
56 | if passwd == pwd:
57 | pass
58 | else:
59 | print 'login incorrect'
60 | return
61 |
62 | print 'welcome back', name
63 |
64 |
65 | #
66 | # showmenu() -- interactive portion of application
67 | # displays menu to prompt user and takes
68 | # action based on user response
69 | #
70 | def showmenu():
71 | prompt = """
72 | (N)ew User Login
73 | (E)xisting User Login
74 | (Q)uit
75 |
76 | Enter choice: """
77 |
78 | # loop until user quits
79 | done = 0
80 | while not done:
81 |
82 | # loop until user choses valid option
83 | chosen = 0
84 | while not chosen:
85 |
86 | # if user hits RETURN/Enter, ^C, or ^D (EOF),
87 | # pretend they typed 'q' to quit normally
88 | try:
89 | choice = raw_input(prompt)[0]
90 | except (EOFError, KeyboardInterrupt):
91 | choice = 'q'
92 | print '\nYou picked: [%s]' % choice
93 |
94 | # validate option chosen
95 | if choice not in 'neq':
96 | print 'invalid menu option, try again'
97 | else:
98 | chosen = 1
99 |
100 | # take appropriate action
101 | if choice == 'q':
102 | done = 1
103 | if choice == 'n':
104 | newuser()
105 | if choice == 'e':
106 | olduser()
107 |
108 |
109 | # run showmenu() as the application
110 | if __name__ == '__main__':
111 | showmenu()
112 |
--------------------------------------------------------------------------------
/ch09/alt/ospathex.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | $Id$
4 |
5 | ospathex.py -- OS path example
6 |
7 | This script test drives many of the operating system module file
8 | and file path functions. The temporary directory is chosen by
9 | the tempfile module. If that does not exist, then there is a
10 | limited set of directory names that are hard-coded as part of
11 | this application. Please add one for your system if this script
12 | cannot find a temporary directory for you.
13 | '''
14 |
15 | import os # operating system module (import real OS module, i.e., posix, nt, etc.)
16 |
17 | def testOSmod(tmpdir):
18 | 'testOSmod(tmpdir) -- test the "os" module with given temporary directory'
19 |
20 | # set working directory
21 | wd = os.path.join(tmpdir, 'example')
22 |
23 | # create and display test subdirectory name
24 | print '*** creating example directory...'
25 | os.mkdir(wd)
26 | print '*** new working directory:'
27 | print wd
28 |
29 | # display test subdirectory listing
30 | print '*** working directory listing:'
31 | print os.listdir(wd)
32 |
33 | # create test file and show updated directory listing
34 | print '*** creating test file...'
35 | testfile = os.path.join(wd, 'test')
36 | file = open(testfile, 'w')
37 | file.write('foo\n')
38 | file.write('bar\n')
39 | file.close()
40 | print '*** updated directory listing:'
41 | print os.listdir(wd)
42 |
43 | # test file rename using os.rename()
44 | print "*** renaming 'test' to 'filetest.txt'"
45 | newtestfile = os.path.join(wd, 'filetest.txt')
46 | os.rename(testfile, newtestfile)
47 | print '*** updated directory listing:'
48 | print os.listdir(wd)
49 |
50 | # test file pathname component join function (os.path.join())
51 | # (join directory name and only file [our test file] in directory)
52 | path = os.path.join(wd, os.listdir(wd)[0])
53 | print '*** full file pathname:'
54 | print path
55 |
56 | # test file pathname split and extension split
57 | print '*** (pathname, basename) == '
58 | print os.path.split(path)
59 | print '*** (filename, extension) == '
60 | print os.path.splitext(os.path.basename(path))
61 |
62 | # display test file contents
63 | print '*** displaying file contents:'
64 | file = open(path)
65 | allLines = file.readlines()
66 | file.close()
67 | for eachLine in allLines:
68 | print eachLine,
69 |
70 | # remove test file, show updated directory listing
71 | print '*** deleting test file'
72 | os.remove(path)
73 | print '*** updated directory listing:'
74 | print os.listdir(wd)
75 |
76 | # delete test directory
77 | print '*** deleting test directory'
78 | os.rmdir(wd)
79 | print '*** DONE'
80 |
81 |
82 | def main():
83 | 'main() -- look for temporary directory and run test'
84 |
85 | # look for a temporary directory; try tempfile module first
86 | try:
87 | from tempfile import gettempdir
88 | tmpdir = gettempdir()
89 |
90 | # if tempfile not available, try a few selected directories
91 | except:
92 | for tmpdir in ('/tmp', 'c:/windows/temp'):
93 | if os.path.isdir(tmpdir):
94 | break
95 |
96 | # otherwise no temporary directory found
97 | else:
98 | print 'no temp directory available'
99 | return
100 |
101 | testOSmod(tmpdir)
102 |
103 |
104 | # run main() if invoked as script
105 | if __name__ == '__main__':
106 | main()
107 |
--------------------------------------------------------------------------------
/ch21/ushuffle_so.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | from random import randrange as rrange
5 | from sqlobject import *
6 | from ushuffle_db import NAMES, randName
7 |
8 | DBNAME = 'test'
9 | COLSIZ = 10
10 | FIELDS = ('login', 'uid', 'prid')
11 |
12 | class MySQLObject(object):
13 | def __init__(self, db, dbName):
14 | import MySQLdb
15 | import _mysql_exceptions
16 | url = 'mysql://localhost/%s' % DBNAME
17 |
18 | while True:
19 | cxn = connectionForURI(url)
20 | sqlhub.processConnection = cxn
21 | #cxn.debug = True
22 | try:
23 | class Users(SQLObject):
24 | class sqlmeta:
25 | fromDatabase = True
26 | login = StringCol(length=8)
27 | uid = IntCol()
28 | prid = IntCol()
29 | break
30 | except _mysql_exceptions.ProgrammingError, e:
31 | class Users(SQLObject):
32 | login = StringCol(length=8)
33 | uid = IntCol()
34 | prid = IntCol()
35 | break
36 | except _mysql_exceptions.OperationalError, e:
37 | cxn1 = sqlhub.processConnection=connectionForURI('mysql://root@localhost')
38 | cxn1.query("CREATE DATABASE %s" % DBNAME)
39 | cxn1.query("GRANT ALL ON %s.* TO ''@'localhost'" % DBNAME)
40 | cxn1.close()
41 | self.users = Users
42 | self.cxn = cxn
43 |
44 | def create(self):
45 | Users = self.users
46 | Users.dropTable(True)
47 | Users.createTable()
48 |
49 | def insert(self):
50 | for who, uid in randName():
51 | self.users(**dict(zip(FIELDS,
52 | [who, uid, rrange(1,5)])))
53 |
54 | def update(self):
55 | fr = rrange(1,5)
56 | to = rrange(1,5)
57 | users = self.users.selectBy(prid=fr)
58 | for i, user in enumerate(users):
59 | user.prid = to
60 | return fr, to, i+1
61 |
62 | def delete(self):
63 | rm = rrange(1,5)
64 | users = self.users.selectBy(prid=rm)
65 | for i, user in enumerate(users):
66 | user.destroySelf()
67 | return rm, i+1
68 |
69 | def dbDump(self):
70 | print '\n%s%s%s' % ('LOGIN'.ljust(COLSIZ),
71 | 'USERID'.ljust(COLSIZ), 'PROJ#'.ljust(COLSIZ))
72 | for usr in self.users.select():
73 | print '%s%s%s' % (tuple([str(getattr(usr,
74 | field)).title().ljust(COLSIZ) \
75 | for field in FIELDS]))
76 |
77 | drop = lambda self: self.users.dropTable()
78 | finish = lambda self: self.cxn.close()
79 |
80 | def main():
81 | print '*** Connecting to %r database' % DBNAME
82 | orm = MySQLObject('mysql', DBNAME)
83 |
84 | print '\n*** Creating users table'
85 | orm.create()
86 |
87 | print '\n*** Inserting names into table'
88 | orm.insert()
89 | orm.dbDump()
90 |
91 | print '\n*** Randomly moving folks',
92 | fr, to, num = orm.update()
93 | print 'from one group (%d) to another (%d)' % (fr, to)
94 | print '\t(%d users moved)' % num
95 | orm.dbDump()
96 |
97 | print '\n*** Randomly choosing group',
98 | rm, num = orm.delete()
99 | print '(%d) to delete' % rm
100 | print '\t(%d users removed)' % num
101 | orm.dbDump()
102 |
103 | print '\n*** Dropping users table'
104 | orm.drop()
105 | orm.finish()
106 |
107 | if __name__ == '__main__':
108 | main()
109 |
--------------------------------------------------------------------------------
/ch21/ushuffle_sa.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | from random import randrange as rrange
5 | from sqlalchemy import *
6 | from ushuffle_db import NAMES, randName
7 |
8 | FIELDS = ('login', 'uid', 'prid')
9 | DBNAME = 'test'
10 | COLSIZ = 10
11 |
12 | class MySQLAlchemy(object):
13 | def __init__(self, db, dbName):
14 | import MySQLdb
15 | import _mysql_exceptions
16 | MySQLdb = pool.manage(MySQLdb)
17 | url = 'mysql://db=%s' % DBNAME
18 | eng = create_engine(url)
19 | try:
20 | cxn = eng.connection()
21 | except _mysql_exceptions.OperationalError, e:
22 | eng1 = create_engine('mysql://user=root')
23 | try:
24 | eng1.execute('DROP DATABASE %s' % DBNAME)
25 | except _mysql_exceptions.OperationalError, e:
26 | pass
27 | eng1.execute('CREATE DATABASE %s' % DBNAME)
28 | eng1.execute(
29 | "GRANT ALL ON %s.* TO ''@'localhost'" % DBNAME)
30 | eng1.commit()
31 | cxn = eng.connection()
32 |
33 | try:
34 | users = Table('users', eng, autoload=True)
35 | except exceptions.SQLError, e:
36 | users = Table('users', eng,
37 | Column('login', String(8)),
38 | Column('uid', Integer),
39 | Column('prid', Integer),
40 | redefine=True)
41 |
42 | self.eng = eng
43 | self.cxn = cxn
44 | self.users = users
45 |
46 | def create(self):
47 | users = self.users
48 | try:
49 | users.drop()
50 | except exceptions.SQLError, e:
51 | pass
52 | users.create()
53 |
54 | def insert(self):
55 | d = [dict(zip(FIELDS,
56 | [who, uid, rrange(1,5)])) for who, uid in randName()]
57 | return self.users.insert().execute(*d).rowcount
58 |
59 | def update(self):
60 | users = self.users
61 | fr = rrange(1,5)
62 | to = rrange(1,5)
63 | return fr, to, \
64 | users.update(users.c.prid==fr).execute(prid=to).rowcount
65 |
66 | def delete(self):
67 | users = self.users
68 | rm = rrange(1,5)
69 | return rm, \
70 | users.delete(users.c.prid==rm).execute().rowcount
71 |
72 | def dbDump(self):
73 | res = self.users.select().execute()
74 | print '\n%s%s%s' % ('LOGIN'.ljust(COLSIZ),
75 | 'USERID'.ljust(COLSIZ), 'PROJ#'.ljust(COLSIZ))
76 | for data in res.fetchall():
77 | print '%s%s%s' % tuple([str(s).title().ljust(COLSIZ) for s in data])
78 |
79 | def __getattr__(self, attr):
80 | return getattr(self.users, attr)
81 |
82 | def finish(self):
83 | self.cxn.commit()
84 | self.eng.commit()
85 |
86 | def main():
87 | print '*** Connecting to %r database' % DBNAME
88 | orm = MySQLAlchemy('mysql', DBNAME)
89 |
90 | print '\n*** Creating users table'
91 | orm.create()
92 |
93 | print '\n*** Inserting names into table'
94 | orm.insert()
95 | orm.dbDump()
96 |
97 | print '\n*** Randomly moving folks',
98 | fr, to, num = orm.update()
99 | print 'from one group (%d) to another (%d)' % (fr, to)
100 | print '\t(%d users moved)' % num
101 | orm.dbDump()
102 |
103 | print '\n*** Randomly choosing group',
104 | rm, num = orm.delete()
105 | print '(%d) to delete' % rm
106 | print '\t(%d users removed)' % num
107 | orm.dbDump()
108 |
109 | print '\n*** Dropping users table'
110 | orm.drop()
111 | orm.finish()
112 |
113 | if __name__ == '__main__':
114 | main()
115 |
--------------------------------------------------------------------------------
/ch20/alt/friends3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | $Id: friends3.py,v 1.1 2000/12/31 01:32:45 wesc Exp $
4 |
5 | Friends CGI demo
6 | '''
7 |
8 | import cgi
9 | from urllib import quote_plus
10 | from string import capwords
11 | #from sys import stderr
12 | #s = stderr.write
13 |
14 | header = 'Content-Type: text/html\n\n'
15 | url = 'http://localhost/cgi-bin/friends3.py'
16 |
17 | errhtml = '''
20 |
55 | You have %s friends.
56 | Click here to edit your data again.
57 | '''
58 |
59 | # doResults() --> None
60 | def doResults(who, howmany):
61 | 'doResults() -- displays results with given form data'
62 |
63 | # substitute in real name and number of friends and return
64 | newurl = url + '?action=reedit&person=%s&howmany=%s' % (quote_plus(who), howmany)
65 | print header + reshtml % (who, who, howmany, newurl)
66 |
67 | # process() --> None
68 | def process():
69 | 'process() does all the work: grabs user data and determines routine to call'
70 |
71 | error = ''
72 |
73 | # initialize Data class object
74 | form = cgi.FieldStorage()
75 | #s('name: '+str(form.name)+'\n')
76 | #s('keys: '+str(form.keys())+'\n')
77 | #for i in form.keys():
78 | #s('item: '+str(form[i].name)+' has a value of '+str(form[i].value)+' and is a ' + form[i].__class__.__name__ + '\n')
79 |
80 | # get user name
81 | if form.has_key('person'):
82 | who = capwords(form['person'].value)
83 | else:
84 | who = 'NEW USER'
85 |
86 | # get name and number of friends
87 | if form.has_key('howmany'):
88 | howmany = form['howmany'].value
89 | else:
90 | if form.has_key('action') and form['action'].value == 'edit':
91 | error = 'Please select the number of friends you have.'
92 | else:
93 | howmany = 0
94 |
95 | # no errors, either display form or present results
96 | if not error:
97 |
98 | # if editing the first time, show results
99 | if form.has_key('action') and form['action'].value != 'reedit':
100 | doResults(who, howmany)
101 |
102 | # otherwise, show form
103 | else:
104 | showForm(who, howmany)
105 |
106 | # send error message back if error situation
107 | else:
108 | showError(error)
109 |
110 |
111 | # invoke if called directly
112 | if __name__ == '__main__':
113 | process()
114 |
--------------------------------------------------------------------------------
/ch19/listdir.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | from time import sleep
5 | from Tkinter import *
6 |
7 | class DirList:
8 |
9 | def __init__(self, initdir=None):
10 | self.top = Tk()
11 | self.label = Label(self.top, \
12 | text='Directory Lister' + ' v1.1')
13 | self.label.pack()
14 |
15 | self.cwd=StringVar(self.top)
16 |
17 | self.dirl = Label(self.top, fg='blue',
18 | font=('Helvetica', 12, 'bold'))
19 | self.dirl.pack()
20 |
21 | self.dirfm = Frame(self.top)
22 | self.dirsb = Scrollbar(self.dirfm)
23 | self.dirsb.pack(side=RIGHT, fill=Y)
24 | self.dirs = Listbox(self.dirfm, height=15, \
25 | width=50, yscrollcommand=self.dirsb.set)
26 | self.dirs.bind('
86 |
99 |
104 | Friends list for: NEW USER
10 | '''
17 |
18 | fradio = ' %s\n'
19 |
20 | def showForm():
21 | friends = ''
22 | for i in [0, 10, 25, 50, 100]:
23 | checked = ''
24 | if i == 0:
25 | checked = 'CHECKED'
26 | friends = friends + fradio % \
27 | (str(i), checked, str(i))
28 |
29 | print header + formhtml % (friends)
30 |
31 | reshtml = '''Friends list for: %s
34 | Your name is: %sFriends list for: NEW USER
14 | '''
21 |
22 | friendradio = ' %s\n'
23 |
24 | def showForm():
25 | friends = ''
26 | for i in [0, 10, 25, 50, 100]:
27 | checked = ''
28 | if i == 0:
29 | checked = 'CHECKED'
30 | friends = friends + friendradio % (str(i), checked, str(i))
31 | print header + formhtml % (friends)
32 |
33 |
34 | reshtml = '''Friends list for: %s
36 | Your name is: %sERROR
13 | %sFriends list for: %s
24 | '''
31 |
32 | fradio = ' %s\n'
33 |
34 | def showForm(who, howmany):
35 | friends = ''
36 | for i in [0, 10, 25, 50, 100]:
37 | checked = ''
38 | if str(i) == howmany:
39 | checked = 'CHECKED'
40 | friends = friends + fradio % \
41 | (str(i), checked, str(i))
42 | print header + formhtml % (who, url, who, friends)
43 |
44 | reshtml = '''Friends list for: %s
47 | Your name is: %sERROR
19 | %sFriends list for: %s
32 | '''
39 |
40 | # showForm() --> None
41 | def showForm(who, howmany):
42 | 'showForm() -- presents blank or data-filled form for new input'
43 |
44 | friends = ''
45 | for i in [0, 10, 25, 50, 100]:
46 | checked = ''
47 | if str(i) == howmany:
48 | checked = 'CHECKED'
49 | friends = friends + friendradio % (str(i), checked, str(i))
50 | print header + formhtml % (who, url, who, friends)
51 |
52 | reshtml = '''Friends list for: %s
54 | Your name is: %sAdvanced CGI Demo Form
17 | '''
31 |
32 | langSet = ('Python', 'PERL', 'Java', 'C++', 'PHP',
33 | 'C', 'JavaScript')
34 | langItem = \
35 | ' %s\n'
36 |
37 | def getCPPCookies(self): # reads cookies from client
38 | if environ.has_key('HTTP_COOKIE'):
39 | for eachCookie in map(strip, \
40 | split(environ['HTTP_COOKIE'], ';')):
41 | if len(eachCookie) > 6 and \
42 | eachCookie[:3] == 'CPP':
43 | tag = eachCookie[3:7]
44 | try:
45 | self.cookies[tag] = \
46 | eval(unquote(eachCookie[8:]))
47 | except (NameError, SyntaxError):
48 | self.cookies[tag] = \
49 | unquote(eachCookie[8:])
50 | else:
51 | self.cookies['info'] = self.cookies['user'] = ''
52 |
53 | if self.cookies['info'] != '':
54 | self.who, langStr, self.fn = \
55 | split(self.cookies['info'], ':')
56 | self.langs = split(langStr, ',')
57 | else:
58 | self.who = self.fn = ''
59 | self.langs = ['Python']
60 |
61 | def showForm(self): # show fill-out form
62 | self.getCPPCookies()
63 | langStr = ''
64 | for eachLang in AdvCGI.langSet:
65 | if eachLang in self.langs:
66 | langStr = langStr + AdvCGI.langItem % \
67 | (eachLang, ' CHECKED', eachLang)
68 | else:
69 | langStr = langStr + AdvCGI.langItem % \
70 | (eachLang, '', eachLang)
71 |
72 | if not self.cookies.has_key('user') or \
73 | self.cookies['user'] == '':
74 | cookieStatus = '(cookie has not been set yet)'
75 | userCook = ''
76 | else:
77 | userCook = cookieStatus = self.cookies['user']
78 |
79 | print AdvCGI.header + AdvCGI.formhtml % (AdvCGI.url,
80 | cookieStatus, userCook, self.who, langStr, self.fn)
81 |
82 | errhtml = '''ERROR
85 | %sYour Uploaded Data
96 | Your cookie value is: %s
97 | Your name is: %s
98 | You can program in the following languages:
99 | %s
100 | Your uploaded file...
103 |
101 | Name: %s
102 | Contents:%s
104 | Click here to return to form.
105 | '''
106 |
107 | def setCPPCookies(self):
108 | for eachCookie in self.cookies.keys():
109 | print 'Set-Cookie: CPP%s=%s; path=/' % \
110 | (eachCookie, quote(self.cookies[eachCookie]))
111 |
112 | def doResults(self):
113 | MAXBYTES = 1024
114 | langlist = ''
115 | for eachLang in self.langs:
116 | langlist = langlist + '
' % eachLang
117 |
118 | filedata = ''
119 | while len(filedata) < MAXBYTES: # read file chunks
120 | data = self.fp.readline()
121 | if data == '': break
122 | filedata = filedata + data
123 | else: # truncate if too long
124 | filedata = filedata + \
125 | '... (file truncated due to size)'
126 | self.fp.close()
127 | if filedata == '':
128 | filedata = \
129 | '(file upload error or file not given)'
130 | filename = self.fn
131 |
132 | if not self.cookies.has_key('user') or \
133 | self.cookies['user'] == '':
134 | cookieStatus = '(cookie has not been set yet)'
135 | userCook = ''
136 | else:
137 | userCook = cookieStatus = self.cookies['user']
138 |
139 | self.cookies['info'] = join([self.who, \
140 | join(self.langs, ','), filename], ':')
141 | self.setCPPCookies()
142 | print AdvCGI.header + AdvCGI.reshtml % \
143 | (cookieStatus, self.who, langlist,
144 | filename, filedata, AdvCGI.url)
145 |
146 | def go(self): # determine which page to return
147 | self.cookies = {}
148 | self.error = ''
149 | form = FieldStorage()
150 | if form.keys() == []:
151 | self.showForm()
152 | return
153 |
154 | if form.has_key('person'):
155 | self.who = capwords(strip(form['person'].value))
156 | if self.who == '':
157 | self.error = 'Your name is required. (blank)'
158 | else:
159 | self.error = 'Your name is required. (missing)'
160 |
161 | if form.has_key('cookie'):
162 | self.cookies['user'] = unquote(strip( \
163 | form['cookie'].value))
164 | else:
165 | self.cookies['user'] = ''
166 |
167 | self.langs = []
168 | if form.has_key('lang'):
169 | langdata = form['lang']
170 | if type(langdata) == type([]):
171 | for eachLang in langdata:
172 | self.langs.append(eachLang.value)
173 | else:
174 | self.langs.append(langdata.value)
175 | else:
176 | self.error = 'At least one language required.'
177 |
178 | if form.has_key('upfile'):
179 | upfile = form["upfile"]
180 | self.fn = upfile.filename or ''
181 | if upfile.file:
182 | self.fp = upfile.file
183 | else:
184 | self.fp = StringIO('(no data)')
185 | else:
186 | self.fp = StringIO('(no file)')
187 | self.fn = ''
188 |
189 | if not self.error:
190 | self.doResults()
191 | else:
192 | self.showError()
193 |
194 | if __name__ == '__main__':
195 | page = AdvCGI()
196 | page.go()
197 |
--------------------------------------------------------------------------------
/ch20/alt/advcgi.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | $Id: advcgi.py,v 1.1 2000/12/31 01:32:45 wesc Exp $
4 |
5 | advcgi.py -- tests CGI file uploads and multi-valued CGI variables
6 |
7 | Advanced CGI demo
8 |
9 | created by wesc on 00/07/25
10 | '''
11 |
12 | from cgi import FieldStorage
13 | from os import environ
14 | from StringIO import StringIO
15 | from urllib import quote, unquote
16 | from string import capwords, strip, split, join
17 | #from sys import stderr
18 | #s = stderr.write
19 |
20 | class AdvCGI:
21 |
22 | header = 'Content-Type: text/html\n\n'
23 | url = '/py/advcgi.py'
24 |
25 | formhtml = '''Advanced CGI Demo Form
28 | '''
42 |
43 | langSet = ('Python', 'PERL', 'Java', 'C++', 'PHP', 'C', 'JavaScript')
44 | langItem = ' %s\n'
45 |
46 |
47 | # reads cookies from client, creates cookies, who, langs
48 | def getCPPCookies(self):
49 | if environ.has_key('HTTP_COOKIE'):
50 | #s('reading cookies from server...\n')
51 | for eachCookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
52 | if len(eachCookie) > 6 and eachCookie[:3] == 'CPP':
53 | tag = eachCookie[3:7]
54 | try:
55 | self.cookies[tag] = eval(unquote(eachCookie[8:]))
56 | except (NameError, SyntaxError):
57 | self.cookies[tag] = unquote(eachCookie[8:])
58 | else:
59 | #s('no cookies on server...\n')
60 | self.cookies['info'] = self.cookies['user'] = ''
61 |
62 | #s('cookies: %s\n' % str(self.cookies))
63 | if self.cookies['info'] != '':
64 | self.who, langStr, self.fn = split(self.cookies['info'], ':')
65 | self.langs = split(langStr, ',')
66 | else:
67 | self.who = self.fn = ''
68 | self.langs = ['Python']
69 |
70 |
71 | def showForm(self):
72 | self.getCPPCookies() # get cookies
73 |
74 | # put together lang checkboxes
75 | langStr = ''
76 | for eachLang in AdvCGI.langSet:
77 | if eachLang in self.langs:
78 | langStr = langStr + AdvCGI.langItem % (eachLang, ' CHECKED', eachLang)
79 | else:
80 | langStr = langStr + AdvCGI.langItem % (eachLang, '', eachLang)
81 |
82 | # see if user cookie set up yet
83 | if not self.cookies.has_key('user') or self.cookies['user'] == '':
84 | cookieStatus = '(cookie has not been set yet)'
85 | userCook = ''
86 | else:
87 | userCook = cookieStatus = self.cookies['user']
88 |
89 | # output results
90 | #s('filename: ' + self.fn + '\n')
91 | print AdvCGI.header + AdvCGI.formhtml % (AdvCGI.url, cookieStatus, userCook, self.who, langStr, self.fn)
92 | #print AdvCGI.header + AdvCGI.formhtml % (AdvCGI.url, cookieStatus, userCook, self.who, langStr)
93 |
94 |
95 | errhtml = '''ERROR
98 | %sYour Uploaded Data
111 | Your cookie value is: %s
112 | Your name is: %s
113 | You can program in the following languages:
114 | %s
115 | Your uploaded file...
118 |
116 | Name: %s
117 | Contents:%s
119 | Click here to return to form.
120 | '''
121 |
122 |
123 | def setCPPCookies(self):
124 | for eachCookie in self.cookies.keys():
125 | #s('setting %s cookie...\n' % eachCookie)
126 | print 'Set-Cookie: CPP%s=%s; path=/' % (eachCookie, quote(self.cookies[eachCookie]))
127 |
128 |
129 | def doResults(self):
130 | MAXBYTES = 1024
131 | langlist = ''
132 | for eachLang in self.langs:
133 | langlist = langlist + '
' % eachLang
134 | filedata = ''
135 | while len(filedata) < MAXBYTES:
136 | data = self.fp.readline()
137 | if data == '': break
138 | filedata = filedata + data
139 | else:
140 | filedata = filedata + '... (file truncated due to size)'
141 | self.fp.close()
142 | if filedata == '':
143 | filedata = '(file upload error or file not given)'
144 | filename = self.fn
145 |
146 | # see if user cookie set up yet
147 | if not self.cookies.has_key('user') or self.cookies['user'] == '':
148 | cookieStatus = '(cookie has not been set yet)'
149 | userCook = ''
150 | else:
151 | userCook = cookieStatus = self.cookies['user']
152 |
153 | # set cookies
154 | self.cookies['info'] = join([self.who, join(self.langs, ','), filename], ':')
155 | self.setCPPCookies()
156 |
157 | # output page
158 | print AdvCGI.header + AdvCGI.reshtml % (cookieStatus, self.who, langlist, filename, filedata, AdvCGI.url)
159 |
160 |
161 | def __init__(self):
162 | self.cookies = {}
163 |
164 |
165 | def go(self):
166 | self.error = ''
167 |
168 | form = FieldStorage()
169 |
170 | if form.keys() == []:
171 | #s('calling showForm()\n')
172 | self.showForm()
173 | return
174 |
175 | if form.has_key('person'):
176 | self.who = capwords(strip(form['person'].value))
177 | if self.who == '':
178 | self.error = 'Your name is required. (blank)'
179 | else:
180 | self.error = 'Your name is required. (missing)'
181 |
182 | if form.has_key('cookie'):
183 | self.cookies['user'] = unquote(strip(form['cookie'].value))
184 | else:
185 | self.cookies['user'] = ''
186 |
187 | self.langs = []
188 | if form.has_key('lang'):
189 | langdata = form['lang']
190 | if type(langdata) == type([]):
191 | for eachLang in langdata:
192 | self.langs.append(eachLang.value)
193 | else:
194 | self.langs.append(langdata.value)
195 | else:
196 | self.error = 'At least one language required.'
197 |
198 | if form.has_key('upfile'):
199 | upfile = form["upfile"]
200 | self.fn = upfile.filename or ''
201 | #s('filename is %s??\n' % self.fn)
202 | if upfile.file:
203 | self.fp = upfile.file
204 | else:
205 | self.fp = StringIO('(no data)')
206 | else:
207 | self.fp = StringIO('(no file)')
208 | self.fn = ''
209 |
210 | if not self.error:
211 | #s('calling doResults()\n')
212 | self.doResults()
213 | else:
214 | #s('calling showError()\n')
215 | self.showError()
216 |
217 |
218 | if __name__ == '__main__':
219 | page = AdvCGI()
220 | page.go()
221 |
--------------------------------------------------------------------------------
/ch20/alt/advcgi2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | $Id: advcgi.py,v 1.1 2000/12/31 01:32:45 wesc Exp $
4 |
5 | advcgi.py -- tests CGI file uploads and multi-valued CGI variables
6 |
7 | Advanced CGI demo
8 |
9 | created by wesc on 00/07/25
10 | '''
11 |
12 | from cgi import FieldStorage
13 | from os import environ
14 | from StringIO import StringIO
15 | from urllib import quote, unquote
16 | #from sys import stderr
17 | #s = stderr.write
18 |
19 | class AdvCGI(object):
20 |
21 | header = 'Content-Type: text/html\n\n'
22 | url = '/py/advcgi.py'
23 |
24 | formhtml = '''Advanced CGI Demo Form
27 | '''
41 |
42 | langSet = ('Python', 'PERL', 'Java', 'C++', 'PHP', 'C', 'JavaScript')
43 | langItem = ' %s\n'
44 |
45 |
46 | # reads cookies from client, creates cookies, who, langs
47 | def getCPPCookies(self):
48 | if environ.has_key('HTTP_COOKIE'):
49 | #s('reading cookies from server...\n')
50 | #for eachCookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
51 | cookies = [x.strip() for x in environ['HTTP_COOKIE'].split(';')]
52 | for eachCookie in cookies:
53 | if len(eachCookie) > 6 and eachCookie[:3] == 'CPP':
54 | tag = eachCookie[3:7]
55 | try:
56 | self.cookies[tag] = eval(unquote(eachCookie[8:]))
57 | except (NameError, SyntaxError):
58 | self.cookies[tag] = unquote(eachCookie[8:])
59 | if not self.cookies.has_key('info'):
60 | self.cookies['info'] = ''
61 | if not self.cookies.has_key('user'):
62 | self.cookies['user'] = ''
63 | else:
64 | #s('no cookies on server...\n')
65 | self.cookies['info'] = self.cookies['user'] = ''
66 |
67 | #s('cookies: %s\n' % str(self.cookies))
68 | if self.cookies['info'] != '':
69 | self.who, langStr, self.fn = self.cookies['info'].split(':')
70 | self.langs = langStr.split(',')
71 | else:
72 | self.who = self.fn = ''
73 | self.langs = ['Python']
74 |
75 |
76 | def showForm(self):
77 | self.getCPPCookies() # get cookies
78 |
79 | # put together lang checkboxes
80 | langStr = ''
81 | for eachLang in AdvCGI.langSet:
82 | if eachLang in self.langs:
83 | langStr = langStr + AdvCGI.langItem % (eachLang, ' CHECKED', eachLang)
84 | else:
85 | langStr = langStr + AdvCGI.langItem % (eachLang, '', eachLang)
86 |
87 | # see if user cookie set up yet
88 | if not self.cookies.has_key('user') or self.cookies['user'] == '':
89 | cookieStatus = '(cookie has not been set yet)'
90 | userCook = ''
91 | else:
92 | userCook = cookieStatus = self.cookies['user']
93 |
94 | # output results
95 | #s('filename: ' + self.fn + '\n')
96 | print AdvCGI.header + AdvCGI.formhtml % (AdvCGI.url, cookieStatus, userCook, self.who, langStr, self.fn)
97 | #print AdvCGI.header + AdvCGI.formhtml % (AdvCGI.url, cookieStatus, userCook, self.who, langStr)
98 |
99 |
100 | errhtml = '''ERROR
103 | %sYour Uploaded Data
116 | Your cookie value is: %s
117 | Your name is: %s
118 | You can program in the following languages:
119 | %s
120 | Your uploaded file...
123 |
121 | Name: %s
122 | Contents:%s
124 | Click here to return to form.
125 | '''
126 |
127 |
128 | def setCPPCookies(self):
129 | for eachCookie in self.cookies.keys():
130 | #s('setting %s cookie...\n' % eachCookie)
131 | print 'Set-Cookie: CPP%s=%s; path=/' % (eachCookie, quote(self.cookies[eachCookie]))
132 |
133 |
134 | def doResults(self):
135 | MAXBYTES = 1024
136 | langlist = ''
137 | for eachLang in self.langs:
138 | langlist = langlist + '
' % eachLang
139 | filedata = ''
140 | while len(filedata) < MAXBYTES:
141 | data = self.fp.readline()
142 | if data == '': break
143 | filedata = filedata + data
144 | else:
145 | filedata = filedata + '... (file truncated due to size)'
146 | self.fp.close()
147 | if filedata == '':
148 | filedata = '(file upload error or file not given)'
149 | filename = self.fn
150 |
151 | # see if user cookie set up yet
152 | if not self.cookies.has_key('user') or self.cookies['user'] == '':
153 | cookieStatus = '(cookie has not been set yet)'
154 | userCook = ''
155 | else:
156 | userCook = cookieStatus = self.cookies['user']
157 |
158 | # set cookies
159 | self.cookies['info'] = ':'.join([self.who, ','.join(self.langs), filename])
160 | self.setCPPCookies()
161 |
162 | # output page
163 | print AdvCGI.header + AdvCGI.reshtml % (cookieStatus, self.who, langlist, filename, filedata, AdvCGI.url)
164 |
165 |
166 | def __init__(self):
167 | self.cookies = {}
168 |
169 |
170 | def go(self):
171 | self.error = ''
172 |
173 | form = FieldStorage()
174 |
175 | if form.keys() == []:
176 | #s('calling showForm()\n')
177 | self.showForm()
178 | return
179 |
180 | if form.has_key('person'):
181 | self.who = form['person'].value.strip().title()
182 | if self.who == '':
183 | self.error = 'Your name is required. (blank)'
184 | else:
185 | self.error = 'Your name is required. (missing)'
186 |
187 | if form.has_key('cookie'):
188 | self.cookies['user'] = unquote(form['cookie'].value.strip())
189 | else:
190 | self.cookies['user'] = ''
191 |
192 | self.langs = []
193 | if form.has_key('lang'):
194 | langdata = form['lang']
195 | if type(langdata) == type([]):
196 | for eachLang in langdata:
197 | self.langs.append(eachLang.value)
198 | else:
199 | self.langs.append(langdata.value)
200 | else:
201 | self.error = 'At least one language required.'
202 |
203 | if form.has_key('upfile'):
204 | upfile = form["upfile"]
205 | self.fn = upfile.filename or ''
206 | #s('filename is %s??\n' % self.fn)
207 | if upfile.file:
208 | self.fp = upfile.file
209 | else:
210 | self.fp = StringIO('(no data)')
211 | else:
212 | self.fp = StringIO('(no file)')
213 | self.fn = ''
214 |
215 | if not self.error:
216 | #s('calling doResults()\n')
217 | self.doResults()
218 | else:
219 | #s('calling showError()\n')
220 | self.showError()
221 |
222 |
223 | if __name__ == '__main__':
224 | page = AdvCGI()
225 | page.go()
226 |
--------------------------------------------------------------------------------