Flask Session API

Session is used to save data between different requests from the same user. Flask implements it using signed cookies by default; the data is stored on the client but cannot be tampered with.

Throughfrom flask import sessionImport and use like a dictionary.


session proxy object

sessionIt is a proxy that points to the SessionMixin instance of the current request. It is only available in the request context.

Attributes/Methods Description
session[key] = value Set session value
session.get(key, default) Safely get a session value, returning default when the key does not exist.
session.pop(key, default) Remove and return the value for the specified key.
session.clear() Clear all session data.
"key" in session Check whether the key exists
session.permanent When set to True, the session persists after the browser is closed (uses PERMANENT_SESSION_LIFETIME)
session.modified When modifying mutable values in session (such as list append), you need to manually set it to True.
session.accessed When True, if the session is accessed, Flask automatically adds the Vary: Cookie header
session.new Whether the session is newly created (some implementations do not support precise detection).

When modifying nested mutable objects in session (such as lists, dictionaries), Flask cannot automatically detect the modification.

Must set manuallysession.modified = TrueOtherwise, the modification will not be saved to the Cookie.


Configuration Item

Configuration Key Default value Description
SECRET_KEY None The secret key for signing the Session; it must be set to use Session.
SESSION_COOKIE_NAME "session" Session Cookie Name
SESSION_COOKIE_DOMAIN None Cookie's Domain attribute
SESSION_COOKIE_PATH None Cookie's Path attribute
SESSION_COOKIE_HTTPONLY True Prevent JavaScript from accessing Session Cookie
SESSION_COOKIE_SECURE False When True, cookies are only sent via HTTPS
SESSION_COOKIE_SAMESITE None "Strict", "Lax", or None
PERMANENT_SESSION_LIFETIME timedelta(days=31) The validity period of a permanent Session.
SESSION_REFRESH_EACH_REQUEST True Refresh the validity period of the Session Cookie on every request.

Code Examples

Example

from flask import Flask, session, redirect, url_for

app = Flask(__name__)
app.secret_key = "your-secret-key"

@app.route("/")
def index():
    if "username" in session:
        return f'Logged in as {session["username"]}'
    return 'You are not logged in'

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        session["username"] = request.form["username"]
        # Set permanent session (keeps for 31 days after browser close)
        session.permanent = True
        return redirect(url_for("index"))
    return '<form method="post"><input name="username"></form>'

@app.route("/appends")
def append_to_list():
    # Note: modifying nested lists requires manually marking modified
    if "items" not in session:
        session["items"] = []
    session["items"].append("new_item")
    session.modified = True  # Must mark manually!
    return f'Items: {session["items"]}'

@app.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("index"))
other extensions