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

2024-09-29 07:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用实现一个http服务器扭曲的.web. 问题来了:有一个登录操作;之后,我希望http服务器记住每个使用acookie/session的客户机,直到用户关闭浏览器。在

我读过扭曲的.web文件,但我不知道怎么做。我知道请求对象有一个名为getSession()的函数,那么会返回一个session对象。下一步呢?如何在多个请求期间存储信息?在

我还搜索了twisted邮件列表;没有什么很有用的,我仍然很困惑。如果以前有人用过这个,请给我解释一下,或者在这里放一些代码,这样我自己就可以理解了。非常感谢你!在


Tags: 文件对象函数用户服务器web信息http
3条回答

你可以用“请求.getSession()”以获取组件化对象。在

您可以阅读更多关于http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentized.html中组件化的信息。使用它的基本方法是通过定义接口和实现,并将on对象推送到会话中。在

请参阅相关问题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()

如果这看起来令人困惑,请不要担心-在这里的行为变得合理之前,您需要了解两件事:

  1. Twisted (Zope) Interfaces & Adapters
  2. Componentized

计数器值存储在适配器类中,接口类记录该类提供的内容。之所以可以在适配器中存储持久数据,是因为Session(由getSession()返回)是Componentized的子类。在

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

getSession() source code

如果客户端已经有一个会话cookie,那么调用getSession()将读取它并返回具有原始会话内容的会话。因此,无论代码是否实际创建会话cookie或只是读取它,它都是透明的。在

会话Cookie具有某些属性。。。如果你想对cookie的内容有更多的控制,那么看看请求.addCookie()getSession()在场景后面调用的。在

相关问题 更多 >