Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 12

###################### 26.2.

4 A simple example <HTML> <HEAD><TITLE>Feedback Form</TITLE></HEAD> <BODY> <P> <FORM ACTION="/cgi-bin/feedback/save_feedback" METHOD="POST"> Type of feedback: <SELECT NAME="feedback_type"> <OPTION> Compliment <OPTION> Criticism </SELECT> </P> <P> Your comments: <TEXTAREA NAME="comments"></TEXTAREA> </P> <INPUT TYPE="SUBMIT" VALUE="Submit Feedback"> </FORM> </BODY> </HTML> #### ------------------------------- File feedback.py ---------------------------"""feedback.py: A simple feedback form application""" def save_feedback(feedback_type, comments): """A function to handle submitted feedback form data""" # Open a file for appending to save the feedback, # creating the file if necessary. try: file=open("feedback_data", "a") except IOError: file=open("feedback_data", "w") # Save the data file.write("Feedback type: %s\n" % feedback_type) file.write("Comments: %s\n\n" % comments) file.close() return "Thank you for your feedback!" #### def mail_feedback(feedback_type, comments): """A function to email submitted feedback form data""" recipients=['admin@mydomain.com'] import smtplib s=smtplib.SMTP("mail.mydomain.com") msg=""" From: webuser@mydomain.com Subject: Feedback %s""" % comments s.sendmail("webuser@mydomain.com", recipients, msg) s.close() return "Thank you for your feedback!" ###################### 26.2.5 Guest books and ad generators

------------------------------- File guestbook.py ---------------------------"""Module guestbook: a simple guestbook application""" class GuestBook: """A guestbook object that provides both the forms and the handling of submitted form data.""" def __init__(self, title, filename): self.title=title self.filename=filename def guestbookForm(self): """Return the guestbook form to the user""" return """<HTML> <HEAD><TITLE>%s</TITLE></HEAD> <BODY> <H2>%s</H2> Please sign our guestbook! <P> <FORM ACTION="signGuestBook" METHOD="POST"> Name: <INPUT TYPE="TEXT" NAME="name"><BR> Email: <INPUT TYPE="TEXT" NAME="email"><BR> <INPUT TYPE="SUBMIT" VALUE="Sign Guestbook"> </FORM> </BODY> </HTML>""" % (self.title, self.title) def successPage(self): """Return a page to thank the user on success""" return """<HTML> <HEAD><TITLE>%s</TITLE></HEAD> <BODY> <H2>Thank you!</H2> Thank you for signing %s! </BODY> </HTML>""" % (self.title, self.title) def signGuestBook(self, name, email='not specified'): """Handle a submitted guestbook form""" # Open a file to save the guestbook entry try: file=open(self.filename, 'a') except IOError: file=open(self.filename, 'w') entry='Guestbook entry: %s %s\n' % (name, email) file.write(entry) file.close() return self.successPage() # Create an instance of a GuestBook myGuestBook=GuestBook('My GuestBook', 'guestbookdata.txt') #### ------------------------------- File guestbook2.py ---------------------------"""guestbook2: a simple guestbook application"""

class GuestBook: """A guestbook object that uses automatic Zope type conversion in its Web form""" def __init__(self, title, filename): self.title=title self.filename=filename def guestbookForm(self): """Return the guestbook form to the user""" return """<HTML> <HEAD><TITLE>%s</TITLE></HEAD> <BODY> <H2>%s</H2> Please sign the guestbook! <P> <FORM ACTION="signGuestBook" METHOD="POST"> Name: <INPUT TYPE="TEXT" NAME="name:required"><BR> Age: <INPUT TYPE="TEXT" NAME="age:int"><BR> Email: <INPUT TYPE="TEXT" NAME="email:required"><BR> Which sports do you like? Check all that apply: <INPUT TYPE="CHECKBOX" NAME="sports:list" VALUE="baseball"> Baseba ll <BR> <INPUT TYPE="CHECKBOX" NAME="sports:list" VALUE="football"> Footba ll <BR> <INPUT TYPE="CHECKBOX" NAME="sports:list" VALUE="basketball"> Bask etball <BR> <INPUT TYPE="CHECKBOX" NAME="sports:list" VALUE="golf"> Golf <BR> <INPUT TYPE="SUBMIT" VALUE="Sign Guestbook"> </FORM> </BODY> </HTML>""" % (self.title, self.title) def successPage(self): """Return a page to thank the user on success""" return """<HTML> <HEAD><TITLE>%s</TITLE></HEAD> <BODY> <H2>%s</H2> Thank you for signing! </BODY> </HTML>""" % (self.title, self.title) def signGuestBook(self, name, age, email, sports): """Handle a submitted guestbook form""" # Open a file to save the guestbook entry try: file=open(self.filename, 'a') except IOError: file=open(self.filename, 'w') # sports will be passed as a list num=len(sports) entry='Guestbook entry: %s %s age %d, likes %d sports.\n' % (name, email, ag e, num) file.write(entry) file.close() return self.successPage()

#### ------------------------------- File ads.py ---------------------------"""ads: a simple random ad generator""" class AdGenerator: """A random ad generator object. It is passed the name of a directory containing ads - files in .gif format""" def __init__(self, ad_dir): self.ads_dir=ad_dir def random_ad(self, RESPONSE): """Return a random ad""" import os, whrandom # Select a random ad file ad_list=os.listdir(self.ad_dir) ad_name=whrandom.choice(ad_list) ad_name=os.path.join(self.ad_dir, ad_name) # Open ad file, using 'rb' to open it in binary mode! ad_file=open(ad_name, 'rb') ad_data=ad_file.read() ad_file.close() # Set the content-type of the response RESPONSE.setHeader('content-type', 'image/gif') return ad_data # Create an instance of the ad generator, # passing the directory where ads are kept generator=AdGenerator('/www/ads/gifs') #### ------------------------------- File ads2.py ---------------------------"""ads2: a fancier random ad generator""" class AdGenerator: """A random ad generator object. It is passed the name of a directory containing ads - files in .gif format""" def __init__(self, ad_dir): self.ads_dir=ad_dir def image_type(self, filename): # This method is not published typemap={'.gif' : 'image/gif', '.jpg' : 'image/jpeg'} ext=filename[-4:] return typemap[ext]

def log_info(self, remote_host, user_agent) # This method is not published try: log=open('log.txt', 'a') except IOError: log=open('log.txt', 'w') line='Host: %s, Browser: %s\n' % (remote_host, user_agent) log.write(line) log.close() def random_ad(self, REQUEST, RESPONSE, last_ad_cookie=''): """Return a random ad""" import os, whrandom # Log some info about this request self.log_info(REQUEST['REMOTE_HOST'], REQUEST['HTTP_USER_AGENT']) # Select a random ad file ad_list=os.listdir(self.ad_dir) ad_name=whrandom.choice(ad_list) ad_name=os.path.join(self.ad_dir, ad_name) # Make sure we dont send the same ad twice in a row if last_ad_cookie: while (last_ad_cookie == ad_name) ad_name=whrandom.choice(ad_list) ad_name=os.path.join(self.ad_dir, ad_name) # Determine the ad type ad_type=self.image_type(ad_name) # Open ad file, using 'rb' to open it in binary mode! ad_file=open(ad_name, 'rb') ad_data=ad_file.read() ad_file.close() # Set a cookie containing the name of the ad served this time RESPONSE.setCookie('last_ad_cookie', ad_name) # Set the content-type of the response RESPONSE.setHeader('content-type', ad_type) return ad_data # Create an instance of the ad generator, # passing the directory where ads are kept generator=AdGenerator('/www/ads/gifs') ###################### 26.3.1 HTML generation with DocumentTemplate ------------------------------- File my_template.dtml ------------------------My name is <!--#var name--> and I am <!--#var age--> years old. #### # create a template from a text file #

template=DocumentTemplate.HTMLFile("my_template.dtml") # render the template # print template(name="Billy", age=77) #### class Person: "A simple person" def __init__(self,name,age): self.name=name self.age=age # create a Person instance # bill=Person("Billy",77) # create a template from a text file # template=DocumentTemplate.HTMLFile("my_template.dtml") # render the template # print template(bill) #### class Person: "A simple person" def __init__(self,name,age): self.name=name self.age=age # document template class attribute # which masquerades as a method index_html=DocumentTemplate.HTMLFile("my_template.dtml") bill=Person("Billy",77) #### You just came from this URL: <!--#var HTTP_REFERER--> And this is the web browser you are using: <!--#var HTTP_USER_AGENT--> ###################### 26.3.2 Conditionals, sequences, and expressions <!--#if old-->I am old.<!--#/if--> #### <!--#if HTTP_REFERER--> You came to this page from <!--#var HTTP_REFERER-->. <!--#else--> You came to this page directly.

<!--#/if--> #### ------------------------------- File people_template.dtml -------------------<!--#in people--> name: <!--#var name--> age: <!--#var age--> <!--#/in--> #### class Person: "A simple person" def __init__(self,name,age): self.name=name self.age=age # define a sequence # my_family=[Person("Billy",77),Person("Pearl", 68),Person("Willard",72)] # define a template # people_template=DocumentTemplate.HTMLFile("people_template.dtml") # render the template # print people_template(people=my_family) #### import DocumentTemplate # define the template # select_template=DocumentTemplate.HTML("""\ <select> <!--#in choices--> <option<!--#if expr="_['sequence-item']==chosen"--> selected<!--#/if-->><!--#var sequence-item--> <!--#/in--> </select>""") # render the template # print select_template(choices=[1,23,55,65,78,99],chosen=55) ###################### 26.3.3 Object Persistence with BoboPOS import BoboPOS class Person(BoboPOS.Persistent): "A persistent person" def __init__(self,name,age): self.name=name self.age=age

# define the object store # object_store=BoboPOS.PickleDictionary("people_store.db") # retrieve billy from the object store # if object_store.has_key("billy"): # if billy is in the object store, then # load it from the object store # billy=object_store["billy"] else: # since billy isn't already in the object # store, we must create the object and # place it in the object store. # billy=object_store["billy"]=Person("Billy",77) # normally Zope will handle transactions, # but in this special case, we need to # commit the transaction to save the new # persistent object # get_transaction().commit() # display the object that we retrieved # from the object store # print billy.name, billy.age ###################### 26.3.3 Object Persistence with BoboPOS ------------------------------- File JobBoard.py -------------------"""JobBoard - An example Zope application JobBoard.py - The module which defines the job listing and job board classes """ from DocumentTemplate import HTMLFile from BoboPOS import Persistent from BoboPOS.PersistentMapping import PersistentMapping import time # location of dtml files dtml_loc="D:\\Zope\\JobBoard\\" class JobBoard(PersistentMapping): """A collection of job postings""" def __init__(self,title): PersistentMapping.__init__(self) self.title=title def values(self): self.expire_listings() return PersistentMapping.values(self)

def expire_listings(self): "delete old job listings" for key,job in self.items(): if job.expired(): del self[key] def add_listing(self,title,description,contact,weeks,REQUEST=None): "add a new job listing - called by add_html" # figure out listing expiry time expires=time.time()+weeks*60*60*24*7 # pick a unique id id=self.unique_key() # create new listing object listing=JobListing(id,title,description,contact,expires) # add new listing self[id]=listing if REQUEST is not None: # if this method is called by Zope, # return a confirmation message return self.confirm_html( message="Job listing successfully added.") def unique_key(self): key=int(time.time()) while self.has_key(key): key=key+1 return str(key) # default HTML method index_html=HTMLFile(dtml_loc+"job_board.dtml") # add a listing HTML form add_html=HTMLFile(dtml_loc+"job_add.dtml") # confirmation HTML confirm_html=HTMLFile(dtml_loc+"confirm.dtml") class JobListing(Persistent): """A job listing""" def __init__(self,id,title,description,contact,expires): "create a new job listing" self.id=id self.title=title self.description=description self.contact=contact self.expires=expires def expired(self): "is this job listing stale?" return time.time() > self.expires # default HTML method index_html=HTMLFile(dtml_loc+"job_listing.dtml") ####

------------------------------- File job_app.py -------------------"""JobBoard - An example Zope application job_app.py - The module which is published by Zope """ import BoboPOS import JobBoard # location of the object store db_loc="D:\\Zope\\JobBoard\\" def create_job_board(): "creates a new job board" db["python_jobs"]=JobBoard.JobBoard("Python Jobs") get_transaction().commit() # define the object store db=BoboPOS.PickleDictionary(db_loc+"job_board.db") if not db.has_key("python_jobs"): # if the object store is empty, # create a new job board object create_job_board() # defines the job board as the # only object published by this # module bobo_application=db["python_jobs"] # show the tracebacks for debugging __bobo_hide_tracebacks__=None #### ------------------------------- File job_board.dtml -------------------<html> <head><title>Job Board: <!--#var title--></title></head> <body bgcolor="#FFFFFF"> <h1>Job Board: <!--#var title--></h1> <h2><a href="add_html">Add a job listing</a></h2> <!--#if values--> <h2>Current job listings</h2> <ul> <!--#in values--> <li><a href="<!--#var id-->"><!--#var title--></a> <!--#/in--> </ul> <!--#else--> <h2>There are currently no job listings.</h2> <!--#/if--> </body> </html> ####

------------------------------- File job_listing.dtml -------------------<html> <head><title>Job Listing: <!--#var title--></title></head> <body bgcolor="#FFFFFF"> <h1>Job Listing: <!--#var title--></h1> <table> <tr><td>Contact:</td><td><!--#var contact--></td></tr> <tr valign="top"><td>Job Description:</td> <td><!--#var description fmt="multi-line"--></td></tr> </table> <p><a href="../index_html">Return</a> to the job board.</p> </body> </html> #### ------------------------------- File confirm.dtml -------------------<html> <head><title>Confirmation</title></head> <body bgcolor="#FFFFFF"> <h1>Confirmation</h1> <p><b><!--#var message--></b></p> <p><a href="index_html">Return</a> to the job board.</p> </body> </html> #### ------------------------------- File job_add.dtml -------------------<html> <head> <title>Add Job Listing: <!--#var title--></title> </head> <body bgcolor="#FFFFFF"> <h1>Add Job Listing: <!--#var title--></h1> <form action="add_listing" method="post"> <table> <tr><td>Job title</td> <td><input type="text" name="title" size=60></td></tr> <tr><td>Job description</td> <td><textarea name="description:text" cols=60 rows=10> </textarea></td></tr> <tr><td>Contact name and email address</td> <td><input type="text" name="contact" size=60></td></tr> <tr><td>Job listing expires in</td> <td><select name="weeks:int"> <option>1 <option>2 <option>3 <option>4 <option>5 <option>6

</select> weeks </td></tr> <tr><td></td> <td><input type="submit" value="Add job listing"></td></tr> </table> </form> </body> </html>

You might also like