Search code examples
python-3.xsessionflasktwistedtwisted.web

storing data in twisted session


I am working to convert example code from Flask to twisted. The flask program is storing data in a session like so:

session['samlUserdata'] = self.auth.get_attributes()
session['samlNameId'] = self.auth.get_nameid()
session['samlSessionIndex'] = self.auth.get_session_index()
session['samlExpiration'] = datetime.now() + timedelta(minutes=SESSION_LENGTH)

In this case session is a flask global, but I want to accomplish the same thing in twisted. Basically I want to store values in my session so I can use that data in other requests.

I know I can access the session data in request.getSession() and have seen some examples of counters but the idea is not translating to what I am trying to do.

Can anyone explain how I would set and retrieve data in a twisted session? As I have said I have seen the counter example and need a more concrete example of how this would be done.

Thanks!


Solution

  • Twisted's session code was conceived long ago and a lot has changed in the web server landscape. I'm not sure if this is the "optimal way" of doing it but you can store session info in a cookie using JWT. Here's an example using klein

    import uuid
    from klein import Klein
    import jwt
    
    router = Klein()
    
    @router.route('/jwt')
    def cookie_magic(request):
        # set cookie if none
        if request.getCookie(b'session_token') is None:
            session_id = uuid.uuid4().hex
            session_token = jwt.encode({'foo': session_id}, '@TODO Secret', algorithm='HS256')
            request.addCookie(b'session_token', session_token)
            return 'session_id set to {0}'.format(session_id)
    
        # get the cookie
        session_token = jwt.decode(request.getCookie(b'session_token'), '@TODO Secret', algorithm='HS256')
        return 'hello {0}'.format(session_token['foo'])
    
    router.run('0.0.0.0', 7777)
    

    This allows you to be more flexible in terms of sessions. For instance if you have another non-twisted web app, you can easily get the session token from the cookie.