存储连接的实例 - twisted.web

时间:2011-02-08 18:45:58

标签: python session twisted twisted.web

我如何在twisted.web中存储连接实例?我见过request.getSession(),但我搜索过,很少有关于如何存储和检索它的例子。

感谢。

更新 我想将ldap连接存储在会话中以便稍后检索

  def render_POST(self, request):

    command = request.path[1:]
    session = request.getSession()

    if command == "authentication":
      Connect = LdapConnection(request.args['host'][0],request.args['user'][0],request.args['password'][0])
      session.addComponent(LdapConnection, Connect)                  

    if command == "users":
      Connect = session.getComponent(LdapConnection)                     
      u = Users(Connect, request.args['name'][0],request.args['employeeNumber'])

    return

1 个答案:

答案 0 :(得分:4)

documentation of twisted中有很多例子。如果您喜欢快速summary on how to use sessions

from twisted.web.resource import Resource

class ShowSession(Resource):
    def render_GET(self, request):
        return 'Your session id is: ' + request.getSession().uid

class ExpireSession(Resource):
    def render_GET(self, request):
        request.getSession().expire()
        return 'Your session has been expired.'

resource = ShowSession()
resource.putChild("expire", ExpireSession())

不要忘记request.getsession()将创建会话(如果它尚不存在)。本教程解释了how to store objects in session

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()