| 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 |
|
|---|
| 26 |
|
|---|
| 27 |
|
|---|
| 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 |
|
|---|
| 37 |
|
|---|
| 38 |
|
|---|
| 39 |
|
|---|
| 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.tree.mount(UsersPage()) |
|---|
| 54 |
|
|---|
| 55 |
|
|---|
| 56 |
if __name__ == '__main__': |
|---|
| 57 |
import os.path |
|---|
| 58 |
thisdir = os.path.dirname(__file__) |
|---|
| 59 |
cherrypy.quickstart(config=os.path.join(thisdir, 'tutorial.conf')) |
|---|