请参阅此相关问题Store an instance of a connection - twisted.web。那里的答案链接到此博客文章http://jcalderone.livejournal.com/53680.html,其中显示了存储会话访问次数计数器的示例(感谢 jcalderone 的示例):
# in a .rpy file launched with `twistd -n web --path .`
cache()
from zope.interface import Interface, Attribute, implements
from twisted.python.components import registerAdapter
from twisted.web.server import Session
from twisted.web.resource import Resource
class ICounter(Interface):
value = Attribute("An int value which counts up once per page view.")
class Counter(object):
implements(ICounter)
def __init__(self, session):
self.value = 0
registerAdapter(Counter, Session, ICounter)
class CounterResource(Resource):
def render_GET(self, request):
session = request.getSession()
counter = ICounter(session)
counter.value += 1
return "Visit #%d for you!" % (counter.value,)
resource = CounterResource()
如果这看起来令人困惑,请不要担心 - 在此处的行为有意义之前,您需要了解两件事:
- Twisted (Zope) 接口和适配器
- 组件化
计数器值存储在适配器类中,接口类记录该类提供的内容。之所以可以在 Adapter 中存储持久数据,是因为 Session(由 getSession() 返回)是 Componentized 的子类。