In this post I’ll provide an example of using session management in Flask. This is useful when you need to recover persistent data across different endpoints in your application. In this example, we set the permanent
attribute of the session
object to True
in order to ensure that the session data lasts indefinitely until it is cleared when the user accesses the root endpoint again. The best practice is to have a timeout on the session data.
Another important feature of this example is the app.secret_key
which ensures that the cookies which the session management is built on top of is cryptographically signed so that users can view the cookies, but not alter them. It’s best to set the secret key to the output of os.urandom(24)
, which should be sufficiently random.
from flask import Flask, render_template, session app.secret_key = "something-from-os.urandom(24)" app = Flask(__name__) @app.before_request def session_management(): # make the session last indefinitely until it is cleared session.permanent = True @app.route("/") def index(): # reset the session data session.clear() session["foo"] = "Foo" return render_template("index.html") @app.route("/foo") def foo(): # retrieve "Foo" from the persistent session object foo = session["foo"] return render_template("foo.html")
Simple and effective, thanks.