session (Flask)

Flask's session is a dictionary-like object that stores per-user data across requests, such as a logged-in user id. By default it is signed and stored in a cookie on the client, so it requires a secret_key.

Flask

HTTP is stateless, so to remember a user between requests Flask uses a session. You assign session['user_id'] = 7 in one request and read it back in the next; behind the scenes Flask serializes the dict, signs it, and stores it in a cookie.

Because the default session lives in a signed cookie, the data is readable by the client (it is not encrypted) but cannot be tampered with without the secret_key. So never put passwords or other secrets in it, and always set a strong secret_key.

For larger or more sensitive session data, use a server-side session extension like Flask-Session that keeps data on the server and stores only an id in the cookie.

Syntax

from flask import session
session["key"] = value
session.get("key")

Examples

Python

from flask import session

app.secret_key = "change-me"

@app.route("/login/<name>")
def login(name):
    session["user"] = name
    return f"Logged in as {name}"

@app.route("/me")
def me():
    return session.get("user", "anonymous")

Learn it in a lesson

See also

Back to the Dictionary