Bundled cherrypy.
[smonitor.git] / monitor / cherrypy / tutorial / tut06_default_method.py
blobfe24f380567044b22176107d0a7dbda31d7ceb40
1 """
2 Tutorial - The default method
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.
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.
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 """
19 import cherrypy
22 class UsersPage:
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
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. :-("
49 return '%s (<a href="./">back</a>)' % out
50 default.exposed = True
53 import os.path
54 tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
56 if __name__ == '__main__':
57 # CherryPy always starts with app.root when trying to map request URIs
58 # to objects, so we need to mount a request handler root. A request
59 # to '/' will be mapped to HelloWorld().index().
60 cherrypy.quickstart(UsersPage(), config=tutconf)
61 else:
62 # This branch is for the test suite; you can ignore it.
63 cherrypy.tree.mount(UsersPage(), config=tutconf)