如何在twisted.web中使用会话/ Cookie?

9 投票
3 回答
4620 浏览
提问于 2025-04-15 12:06

我正在用 twisted.web 实现一个 HTTP 服务器。现在遇到一个问题:有一个登录操作;之后,我希望 HTTP 服务器能记住每个用户,使用 cookie 或会话,直到用户关闭浏览器。

我看过 twisted.web 的文档,但还是搞不清楚该怎么做。我知道请求对象有一个叫 getSession() 的函数,调用后会返回一个会话对象。那么接下来该怎么做呢?我该如何在多次请求中存储信息呢?

我也在 twisted 的邮件列表里搜索过,但没有找到什么有用的,还是很困惑。如果有人之前用过这个,请给我解释一下,或者甚至给我一些代码,这样我就能自己理解了。非常感谢!

3 个回答

3

可以看看这个相关的问题 如何存储一个连接的实例 - 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()

如果这看起来有点复杂,不用担心 - 在理解这里的行为之前,你需要明白两件事:

  1. Twisted (Zope) 接口和适配器
  2. 组件化

计数器的值存储在一个适配器类中,而接口类则说明了这个类提供了什么功能。你之所以能在适配器中存储持久数据,是因为会话(通过getSession()返回的)是组件化的一个子类。

4

调用 getSession() 会生成一个会话,并把 cookie 加到请求中:

getSession() 源代码

如果客户端已经有一个会话 cookie,那么调用 getSession() 会读取这个 cookie,并返回一个包含原始会话内容的 Session。所以,不管是实际创建会话 cookie 还是只是读取它,这对你的代码来说都是透明的,也就是说你不需要特别关心。

会话 cookie 有一些特定的属性……如果你想对 cookie 的内容有更多的控制,可以看看 Request.addCookie(),这个方法是 getSession() 在后台调用的。

4

你可以用 "request.getSession()" 来获取一个组件化的对象。

想了解更多关于组件化的内容,可以查看这个链接:http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentized.html。基本的使用方法是先定义一个接口和一个实现,然后把你的对象放进会话里。

撰写回答