bonus-sqlobject.py (3305B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\lib\cherrypy\tutorial\bonus-sqlobject.py 2 import cherrypy 3 from Cheetah.Template import Template 4 from sqlobject import * 5 __connection__ = 'mysql://root:@localhost/test' 6 7 class Contact(SQLObject): 8 lastName = StringCol(length=50, notNone=True) 9 firstName = StringCol(length=50, notNone=True) 10 phone = StringCol(length=30, notNone=True, default='') 11 email = StringCol(length=30, notNone=True, default='') 12 url = StringCol(length=100, notNone=True, default='') 13 14 15 class ContactManager: 16 17 def index(self): 18 contacts = Contact.select() 19 template = Template('\n <h2>All Contacts</h2>\n\n #for $contact in $contacts\n <a href="mailto:$contact.email">$contact.lastName, $contact.firstName</a>\n [<a href="./edit?id=$contact.id">Edit</a>]\n [<a href="./delete?id=$contact.id">Delete</a>]\n <br/>\n #end for\n\n <p>[<a href="./edit">Add new contact</a>]</p>\n ', [locals(), globals()]) 20 return template.respond() 21 22 index.exposed = True 23 24 def edit(self, id = 0): 25 id = int(id) 26 if id > 0: 27 contact = Contact.get(id) 28 title = 'Edit Contact' 29 else: 30 contact = None 31 title = 'New Contact' 32 template = Template('\n <h2>$title</h2>\n\n <form action="./store" method="POST">\n <input type="hidden" name="id" value="$id" />\n Last Name: <input name="lastName" value="$getVar(\'contact.lastName\', \'\')" /><br/>\n First Name: <input name="firstName" value="$getVar(\'contact.firstName\', \'\')" /><br/>\n Phone: <input name="phone" value="$getVar(\'contact.phone\', \'\')" /><br/>\n Email: <input name="email" value="$getVar(\'contact.email\', \'\')" /><br/>\n URL: <input name="url" value="$getVar(\'contact.url\', \'\')" /><br/>\n <input type="submit" value="Store" />\n </form>\n ', [locals(), globals()]) 33 return template.respond() 34 35 edit.exposed = True 36 37 def delete(self, id): 38 contact = Contact.get(int(id)) 39 contact.destroySelf() 40 return 'Deleted. <a href="./">Return to Index</a>' 41 42 delete.exposed = True 43 44 def store(self, lastName, firstName, phone, email, url, id = None): 45 if id and int(id) > 0: 46 contact = Contact.get(int(id)) 47 contact.set(lastName=lastName, firstName=firstName, phone=phone, email=email, url=url) 48 else: 49 contact = Contact(lastName=lastName, firstName=firstName, phone=phone, email=email, url=url) 50 return 'Stored. <a href="./">Return to Index</a>' 51 52 store.exposed = True 53 54 def reset(self): 55 Contact.dropTable(True) 56 Contact.createTable() 57 Contact(firstName='Hendrik', lastName='Mans', email='hendrik@mans.de', phone='++49 89 12345678', url='http://www.mornography.de') 58 return 'reset completed!' 59 60 reset.exposed = True 61 62 63 print "If you're running this application for the first time, please go to http://localhost:8080/reset once in order to create the database!" 64 cherrypy.quickstart(ContactManager())