|
Revision 130
(checked in by rdelon, 4 years ago)
|
--
|
| Line | |
|---|
| 1 |
""" |
|---|
| 2 |
Tutorial 06 - Aspects |
|---|
| 3 |
|
|---|
| 4 |
CherryPy2 aspects let you dynamically alter a request handler object's |
|---|
| 5 |
behaviour by adding code that gets executed before and/or after |
|---|
| 6 |
requested methods. This is useful in situations where you need common |
|---|
| 7 |
method behavior across multiple methods or even objects (aspects can |
|---|
| 8 |
be part of derived classes). |
|---|
| 9 |
""" |
|---|
| 10 |
|
|---|
| 11 |
from cherrypy import cpg |
|---|
| 12 |
|
|---|
| 13 |
|
|---|
| 14 |
from cherrypy.lib.aspect import Aspect, STOP, CONTINUE |
|---|
| 15 |
|
|---|
| 16 |
|
|---|
| 17 |
class Page(Aspect): |
|---|
| 18 |
title = 'Untitled Page' |
|---|
| 19 |
|
|---|
| 20 |
def header(self): |
|---|
| 21 |
|
|---|
| 22 |
return ''' |
|---|
| 23 |
<html> |
|---|
| 24 |
<head> |
|---|
| 25 |
<title>%s</title> |
|---|
| 26 |
<head> |
|---|
| 27 |
<body> |
|---|
| 28 |
<h2>%s</h2> |
|---|
| 29 |
''' % (self.title, self.title) |
|---|
| 30 |
|
|---|
| 31 |
def footer(self): |
|---|
| 32 |
|
|---|
| 33 |
return ''' |
|---|
| 34 |
</body> |
|---|
| 35 |
</html> |
|---|
| 36 |
''' |
|---|
| 37 |
|
|---|
| 38 |
def _before(self, methodName, method): |
|---|
| 39 |
|
|---|
| 40 |
|
|---|
| 41 |
|
|---|
| 42 |
|
|---|
| 43 |
if methodName not in ['header', 'footer']: |
|---|
| 44 |
return CONTINUE, self.header() |
|---|
| 45 |
else: |
|---|
| 46 |
return CONTINUE, '' |
|---|
| 47 |
|
|---|
| 48 |
def _after(self, methodName, method): |
|---|
| 49 |
|
|---|
| 50 |
|
|---|
| 51 |
|
|---|
| 52 |
if getattr(method, 'exposed', False) and methodName not in ['header', 'footer']: |
|---|
| 53 |
return CONTINUE, self.footer() |
|---|
| 54 |
else: |
|---|
| 55 |
|
|---|
| 56 |
|
|---|
| 57 |
return CONTINUE, '' |
|---|
| 58 |
|
|---|
| 59 |
|
|---|
| 60 |
|
|---|
| 61 |
class HomePage(Page): |
|---|
| 62 |
title = 'Tutorial 6 -- Aspect Powered!' |
|---|
| 63 |
|
|---|
| 64 |
def __init__(self): |
|---|
| 65 |
self.another = AnotherPage() |
|---|
| 66 |
|
|---|
| 67 |
def index(self): |
|---|
| 68 |
|
|---|
| 69 |
|
|---|
| 70 |
|
|---|
| 71 |
return ''' |
|---|
| 72 |
<p> |
|---|
| 73 |
Isn't this exciting? There's |
|---|
| 74 |
<a href="./another/">another page</a>, too! |
|---|
| 75 |
</p> |
|---|
| 76 |
''' |
|---|
| 77 |
|
|---|
| 78 |
index.exposed = True |
|---|
| 79 |
|
|---|
| 80 |
|
|---|
| 81 |
class AnotherPage(Page): |
|---|
| 82 |
title = 'Another Page' |
|---|
| 83 |
|
|---|
| 84 |
def index(self): |
|---|
| 85 |
|
|---|
| 86 |
return ''' |
|---|
| 87 |
<p> |
|---|
| 88 |
And this is the amazing second page! |
|---|
| 89 |
</p> |
|---|
| 90 |
''' |
|---|
| 91 |
|
|---|
| 92 |
index.exposed = True |
|---|
| 93 |
|
|---|
| 94 |
|
|---|
| 95 |
cpg.root = HomePage() |
|---|
| 96 |
|
|---|
| 97 |
cpg.server.start(configFile = 'tutorial.conf') |
|---|