## page was renamed from CherrPyTut/08 sessions.py
##language:zh
{{{#!python
# -*- coding: utf-8 -*-
"""
Tutorial 08 - 对话
保存对话信息在 CP2 中非常的简单:
cpg.request 提供了一个字典对象叫 sessionMap 记录了当前用户的会话数据.
如果你使用的是内存(RAM)式的会话,你可以保存任何类型的对象在此字典中;
否则,你将限制只能保持可以被线性化的对象.
"""
from cherrypy import cpg
#改造,增加 Aspect机制
from cherrypy.lib.aspect import Aspect, STOP, CONTINUE
class Page(Aspect):
"""要求从 Aspect 继承类
"""
title = 'Untitled Page'
def __init__(self):
"""增加全局性点击计数对象
"""
self.count = 0
def _count(self):
"""想简单的增加统一的计数函式,发现不行!
"""
# 创建无聊的点击计数
self.count = cpg.request.sessionMap.get('count', 0) + 1
# 记录计数在会话对象中
cpg.request.sessionMap['count'] = self.count
def header(self):
"""强调页面编码
"""
return '''
%s
%s
''' % (self.title, self.title)
def footer(self):
return '''
'''
def _before(self, methodName, method):
"""投影函式 _before 会在任何函式运行时被调用,如果你有一些函式不想如此处理
可以在调用前检测一下
"""
#self.count = cpg.request.sessionMap.get('count', 0) + 1
if methodName not in ['header', 'footer']:
return CONTINUE, self.header()
else:
return CONTINUE, ''
def _after(self, methodName, method):
"""同上投影函式 _after 是在任何函式运行后自动调用
"""
#cpg.request.sessionMap['count'] = self.count
if methodName not in ['header', 'footer']:
return CONTINUE, self.footer()
else:
return CONTINUE, ''
class HitCounter(Page):
"""点击计数页面对象
"""
title = '点击计数 尝试页面!'
def __init__(self):
"""直接增加下层对象
"""
self.deep = DeepPage()
def index(self):
# 创建无聊的点击计数
self.count = cpg.request.sessionMap.get('count', 0) + 1
# 记录计数在会话对象中
cpg.request.sessionMap['count'] = self.count
#self._count()
# 在页面中显示计数信息
return '''
During your current session, you've viewed this
page %s times! Your life is a patio of fun!
goto deep page count again!?
deep page
''' % self.count
index.exposed = True
class DeepPage(Page):
"""下层对象的展示
"""
title = 'DeepPage base AnotherPage'
def index(self):
#self._count()
# 创建无聊的点击计数
self.count = cpg.request.sessionMap.get('count', 0) + 1
# 记录计数在会话对象中
cpg.request.sessionMap['count'] = self.count
return '''
在下层对象中继续计数!
:%s
go back
'''% self.count
index.exposed = True
cpg.root = HitCounter()
cpg.server.start(configFile = 'tutorial.conf')
}}}