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

root/branches/cherrypy-2.1/cherrypy/tutorial/tut06_default_method.py

Revision 727 (checked in by fumanchu, 3 years ago)

Tutorial fixes, plus a bug in _cputil.getErrorPage.

Line 
1 """
2 Tutorial - 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 cherrypy.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 import cherrypy
20
21
22 class UsersPage:
23    
24     def index(self):
25         # Since this is just a stupid little example, we'll simply
26         # display a list of links to random, made-up users. In a real
27         # application, this could be generated from a database result set.
28         return '''
29             <a href="./remi">Remi Delon</a><br/>
30             <a href="./hendrik">Hendrik Mans</a><br/>
31             <a href="./lorenzo">Lorenzo Lamas</a><br/>
32         '''
33     index.exposed = True
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     default.exposed = True
51
52
53 cherrypy.root = UsersPage()
54
55
56 if __name__ == '__main__':
57     cherrypy.config.update(file = 'tutorial.conf')
58     cherrypy.server.start()
59
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets