pythonsessionfalconframework

Falcon framework - how to store variables in a session?


I need to store the current user id in the session in my Falcon application. In Flask I would do:

from flask import Flask, session

app = Flask(__name__)

@app.route('/')
def example():
    session['foo'] = 'bar'
    return 'bar'

@app.route('/bar')
def bar():
    return session.get('foo')

I would like to be able to do something similar in Falcon:

class ExampleResource(object):

    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.body = 'bar'
        self.session['foo'] = 'bar'

How can I accomplish something like this in Falcon?


Solution

  • From the source code, we learn that Flask uses client side session which is based on secure cookies.

    Thus we could achieve the same thing by using Falcon Cookies API which also uses secure cookies by default.

    class ExampleResource(object):
    
        def on_get(self, req, resp):
            resp.set_cookie('foo', 'bar')
            resp.body = 'bar'
    
    
    class BarResource(object):
    
        def on_get(self, req, resp):
            resp.body = req.cookies.get('foo')