我正在使用twisted.web实现http服务器。问题来了:有一个登录操作;之后,我希望http服务器使用cookie /会话记住每个客户端,直到用户关闭浏览器为止。
我已经阅读了twisted.web文档,但是我不知道该怎么做。我知道请求对象有一个名为getSession()的函数,然后将返回一个会话对象。接下来是什么?在多个请求期间如何存储信息?
我还搜索了扭曲的邮件列表;没有什么非常有用的,我仍然感到困惑。如果有人以前使用过此功能,请向我解释,甚至在此处放置一些代码,以便我自己理解。非常感谢你!
您可以使用“ request.getSession()”来获取组件化的对象。
您可以在http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentized.html中了解有关组件化的更多信息-使用它的基本方法是通过定义接口和实现,并将对象放在会话中。
调用getSession()将生成一个会话并将cookie添加到请求中:
如果客户端已经具有会话cookie,则调用getSession()将读取它并返回具有原始Session内容的Session。因此,无论是实际上创建会话cookie还是只是读取它,对于您的代码都是透明的。
会话cookie具有某些属性...如果您想进一步控制cookie的内容,请查看Request.addCookie(),该方法在后台调用了getSession()。
请参阅此相关问题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()
不要担心,这似乎令人困惑-在这里的行为有意义之前,您需要了解两件事:
计数器值存储在Adapter类中,Interface类记录该类提供的内容。之所以可以在适配器中存储持久数据,是因为Session(由getSession()返回)是Componentized的子类。