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

root/tags/cherrypy-2.0.0/cherrypy/tutorial/07_default_method.py

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

add descriptive names to the tutorials

Line 
1 """
2 Tutorial 07 - The default method
3
4 Request handler objects can implement a method called "default" that
5 is called when no other suitable method/object could be found.
6 Essentially, if CherryPy2 can't find a matching request handler object
7 for the given request URI, it will use the default method of the object
8 located deepest on the URI path.
9
10 Using this mechanism you can easily simulate virtual URI structures
11 by parsing the extra URI string, which you can access through
12 cpg.request.virtualPath.
13
14 The application in this tutorial simulates an URI structure looking
15 like /users/<username>. Since the <username> bit will not be found (as
16 there are no matching methods), it is handled by the default method.
17 """
18
19 from cherrypy import cpg
20
21 class UsersPage:
22     def index(self):
23         # Since this is just a stupid little example, we'll simply
24         # display a list of links to random, made-up users. In a real
25         # application, this could be generated from a database result set.
26         return '''
27             <a href="./remi">Remi Delon</a><br/>
28             <a href="./hendrik">Hendrik Mans</a><br/>
29             <a href="./lorenzo">Lorenzo Lamas</a><br/>
30         '''
31
32     index.exposed = True
33
34
35     def default(self, user):
36         # Here we react depending on the virtualPath -- the part of the
37         # path that could not be mapped to an object method. In a real
38         # application, we would probably do some database lookups here
39         # instead of the silly if/elif/else construct.
40         if user == 'remi':
41             out = "Remi Delon, CherryPy lead developer"
42         elif user == 'hendrik':
43             out = "Hendrik Mans, CherryPy co-developer & crazy German"
44         elif user == 'lorenzo':
45             out = "Lorenzo Lamas, famous actor and singer!"
46         else:
47             out = "Unknown user. :-("
48
49         return '%s (<a href="./">back</a>)' % out
50
51     default.exposed = True
52
53
54 cpg.root = UsersPage()
55
56 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