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

root/tags/cherrypy-2.0.0/cherrypy/tutorial/05_derived_objects.py

Revision 102 (checked in by dpotter, 4 years ago)

add descriptive names to the tutorials

Line 
1 """
2 Tutorial 05 - Object inheritance
3
4 You are free to derive your request handler classes from any base
5 class you wish. In most real-world applications, you will probably
6 want to create a central base class used for all your pages, which takes
7 care of things like printing a common page header and footer.
8 """
9
10 from cherrypy import cpg
11
12 class Page:
13     # Store the page title in a class attribute
14     title = 'Untitled Page'
15
16     def header(self):
17         return '''
18             <html>
19             <head>
20                 <title>%s</title>
21             <head>
22             <body>
23             <h2>%s</h2>
24         ''' % (self.title, self.title)
25
26     def footer(self):
27         return '''
28             </body>
29             </html>
30         '''
31
32     # Note that header and footer don't get their exposed attributes
33     # set to True. This isn't necessary since the user isn't supposed
34     # to call header or footer directly; instead, we'll call them from
35     # within the actually exposed handler methods defined in this
36     # class' subclasses.
37
38
39 class HomePage(Page):
40     # Different title for this page
41     title = 'Tutorial 5'
42
43     def __init__(self):
44         # create a subpage
45         self.another = AnotherPage()
46
47     def index(self):
48         # Note that we call the header and footer methods inherited
49         # from the Page class!
50         return self.header() + '''
51             <p>
52             Isn't this exciting? There's
53             <a href="./another/">another page</a>, too!
54             </p>
55         ''' + self.footer()
56
57     index.exposed = True
58
59
60 class AnotherPage(Page):
61     title = 'Another Page'
62
63     def index(self):
64         return self.header() + '''
65             <p>
66             And this is the amazing second page!
67             </p>
68         ''' + self.footer()
69
70     index.exposed = True
71
72
73 cpg.root = HomePage()
74
75 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