Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/tags/cherrypy-2.0.0/cherrypy/tutorial/09_generators_and_yield.py

Revision 115 (checked in by rdelon, 4 years ago)

Removed GeneratorFilter? (this is now part of the core) and updated generator tutorial

Line 
1 """
2 Bonus Tutorial: Using generators to return result bodies
3
4 Instead of returning a complete result string, you can use the yield
5 statement to return one result part after another. This may be convenient
6 in situations where using a template package like CherryPy or Cheetah
7 would be overkill, and messy string concatenation too uncool. ;-)
8 """
9
10 from cherrypy import cpg
11
12 class GeneratorDemo:
13     def header(self):
14         return "<html><body><h2>Generators rule!</h2>"
15    
16     def footer(self):
17         return "</body></html>"
18    
19     def index(self):
20         # Let's make up a list of users for presentation purposes
21         users = ['Remi', 'Carlos', 'Hendrik', 'Lorenzo Lamas']
22
23         # Every yield line adds one part to the total result body.
24         yield self.header()
25         yield "<h3>List of users:</h3>"
26        
27         for user in users:
28             yield "%s<br/>" % user
29            
30         yield self.footer()
31
32     index.exposed = True
33
34 cpg.root = GeneratorDemo()
35 cpg.server.start(configFile = 'tutorial.conf')
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets