Store an instance of a connection - twisted.web

前端 未结 1 1725
悲哀的现实
悲哀的现实 2021-01-24 20:36

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.<

相关标签:
1条回答
  • 2021-01-24 21:27

    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()
    
    0 讨论(0)
提交回复
热议问题