1

How I store an instance of a connection in twisted.web? I have seen request.getSession() but I searched and there are very few examples of how it is stored and retrieved later.

Thanks.

Update: I want to store the ldap connection in a session for retrieve later

  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
2
  • could you give more details in your question? give an example of code of what you are trying to achieve and what is not currently working for you?
    – karlcow
    Commented Feb 8, 2011 at 22:30
  • I update with sample code. Thanks a lot :)
    – Manu Mora
    Commented Feb 8, 2011 at 23:05

1 Answer 1

4

There are plenty of examples in the documentation of twisted. If you prefer a quick 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())

Do not forget that request.getsession() will create the session if it doesn't already exists. This tutorial explains 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()
1
  • 1
    @ManuMora, Twisted (Zope) Interfaces & Adapters are confusing at first, but are in common use so it's helpful to have an understanding of how they work. The reason that you can store persistent data in the adapter here is that Session subclasses Componentized Commented May 25, 2012 at 3:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.