Bundled cherrypy.
[smonitor.git] / monitor / cherrypy / tutorial / tut04_complex_site.py
blobb4d820ed7a07107f7c709329b7055b3fc2b06c56
1 """
2 Tutorial - Multiple objects
4 This tutorial shows you how to create a site structure through multiple
5 possibly nested request handler objects.
6 """
8 import cherrypy
11 class HomePage:
12 def index(self):
13 return '''
14 <p>Hi, this is the home page! Check out the other
15 fun stuff on this site:</p>
17 <ul>
18 <li><a href="/joke/">A silly joke</a></li>
19 <li><a href="/links/">Useful links</a></li>
20 </ul>'''
21 index.exposed = True
24 class JokePage:
25 def index(self):
26 return '''
27 <p>"In Python, how do you create a string of random
28 characters?" -- "Read a Perl file!"</p>
29 <p>[<a href="../">Return</a>]</p>'''
30 index.exposed = True
33 class LinksPage:
34 def __init__(self):
35 # Request handler objects can create their own nested request
36 # handler objects. Simply create them inside their __init__
37 # methods!
38 self.extra = ExtraLinksPage()
40 def index(self):
41 # Note the way we link to the extra links page (and back).
42 # As you can see, this object doesn't really care about its
43 # absolute position in the site tree, since we use relative
44 # links exclusively.
45 return '''
46 <p>Here are some useful links:</p>
48 <ul>
49 <li><a href="http://www.cherrypy.org">The CherryPy Homepage</a></li>
50 <li><a href="http://www.python.org">The Python Homepage</a></li>
51 </ul>
53 <p>You can check out some extra useful
54 links <a href="./extra/">here</a>.</p>
56 <p>[<a href="../">Return</a>]</p>
57 '''
58 index.exposed = True
61 class ExtraLinksPage:
62 def index(self):
63 # Note the relative link back to the Links page!
64 return '''
65 <p>Here are some extra useful links:</p>
67 <ul>
68 <li><a href="http://del.icio.us">del.icio.us</a></li>
69 <li><a href="http://www.mornography.de">Hendrik's weblog</a></li>
70 </ul>
72 <p>[<a href="../">Return to links page</a>]</p>'''
73 index.exposed = True
76 # Of course we can also mount request handler objects right here!
77 root = HomePage()
78 root.joke = JokePage()
79 root.links = LinksPage()
81 # Remember, we don't need to mount ExtraLinksPage here, because
82 # LinksPage does that itself on initialization. In fact, there is
83 # no reason why you shouldn't let your root object take care of
84 # creating all contained request handler objects.
87 import os.path
88 tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
90 if __name__ == '__main__':
91 # CherryPy always starts with app.root when trying to map request URIs
92 # to objects, so we need to mount a request handler root. A request
93 # to '/' will be mapped to HelloWorld().index().
94 cherrypy.quickstart(root, config=tutconf)
95 else:
96 # This branch is for the test suite; you can ignore it.
97 cherrypy.tree.mount(root, config=tutconf)