1 # -*- coding: gbk -*-
   2 """
   3 Tutorial 06 - Aspects
   4 
   5 CherryPy2 的 投影机制 可以让你动态的在响应请求之前和之后 增加一些代码.
   6 这对于 多个函式或是类需要共同的行为情景非常有用!
   7 (aspects can be part of derived classes).
   8 """
   9 
  10 from cherrypy import cpg
  11 
  12 # 只要简单的引用 CP2 提供的附加对象就可以实际支持
  13 from cherrypy.lib.aspect import Aspect, STOP, CONTINUE
  14 
  15 class Page(Aspect):
  16     """要求从 Aspect 继承类
  17     """
  18     title = 'Untitled Page'
  19 
  20     def header(self):
  21         """与05_derived_objects.py相同的代码
  22         """
  23         return '''
  24             <html>
  25             <head>
  26                 <title>%s</title>
  27             <head>
  28             <body>
  29             <h2>%s</h2>
  30         ''' % (self.title, self.title)
  31 
  32     def footer(self):
  33         return '''
  34             </body>
  35             </html>
  36         '''
  37 
  38     def _before(self, methodName, method):
  39         """投影函式 _before 会在任何函式运行时被调用,如果你有一些函式不想如此处理
  40         可以在调用前检测一下
  41         """
  42         if methodName not in ['header', 'footer']:
  43             return CONTINUE, self.header()
  44         else:
  45             return CONTINUE, ''
  46 
  47     def _after(self, methodName, method):
  48         """同上投影函式 _after 是在任何函式运行后自动调用
  49         """
  50         if methodName not in ['header', 'footer']:
  51             return CONTINUE, self.footer()
  52         else:
  53             return CONTINUE, ''
  54 
  55 class HomePage(Page):
  56     title = 'Tutorial 6 -- Aspect Powered!'
  57 
  58     def __init__(self):
  59         """初始化下层页面引用
  60         """
  61         self.another = AnotherPage()
  62 
  63     def index(self):
  64         """注意!这里我们不用调用 header 和 footer
  65             - 从Page 继承爱厂如家类都会被 投影机制 自动处理
  66         """
  67         return '''
  68             <p>
  69             Isn't this exciting? There's
  70             <a href="./another/">another page</a>, too!
  71             </p>
  72         '''
  73 
  74     index.exposed = True
  75 
  76 
  77 class AnotherPage(Page):
  78     title = 'Another Page'
  79 
  80     def __init__(self):
  81         self.deep = DeepPage()
  82 
  83     def index(self):
  84         # See above. No header or footer methods called!
  85         return '''
  86             <p>
  87             And this is the amazing second page!
  88             </p>
  89             <!--我添加的再下层链接-->
  90             <a href="deep">deep goon!</a>
  91         '''
  92     index.exposed = True
  93 
  94 class DeepPage(Page):
  95     title = 'Deep Page'
  96 
  97     def index(self):
  98         # 同上层一样的处理,没有 head 和 foot 的调用!
  99         return '''
 100             <p>
 101             And this is the amazing 3td page!
 102             </p>
 103         '''
 104     index.exposed = True
 105 
 106 cpg.root = HomePage()
 107 
 108 cpg.server.start(configFile = 'tutorial.conf')