Skip to main content

SecureCookieSession

Base class for sessions based on signed cookies. This session backend will set the modified and accessed attributes. It cannot reliably track whether a session is new (vs. empty), so new remains hard coded to False.
class SecureCookieSession(CallbackDict[str, Any], SessionMixin)

Attributes

modified

When data is changed, this is set to True. Only the session dictionary itself is tracked; if the session contains mutable data (for example a nested dict) then this must be set to True manually when modifying that data. The session cookie will only be written to the response if this is True.
  • Type: bool
  • Default: False

Constructor

SecureCookieSession(initial: Mapping[str, Any] | None = None)
initial
Mapping[str, Any] | None
default:"None"
Initial data for the session

SessionMixin

Expands a basic dictionary with session attributes. This is the base for all session implementations.

Properties

permanent

session.permanent -> bool
This reflects the '_permanent' key in the dict. When set to True, the session will use the PERMANENT_SESSION_LIFETIME config value for expiration.
from flask import session

@app.route('/login', methods=['POST'])
def login():
    # Authenticate user...
    session['user_id'] = 123
    session.permanent = True  # Session persists beyond browser close
    return 'Logged in'

new

Some implementations can detect whether a session is newly created, but that is not guaranteed. Use with caution. The mixin default is hard-coded False.
  • Type: bool
  • Default: False

modified

Some implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to True.
  • Type: bool
  • Default: True

accessed

Indicates if the session was accessed, even if it was not modified. This is set when the session object is accessed through the request context, including the global session proxy. A Vary: cookie header will be added if this is True.
  • Type: bool
  • Default: False
Changed in 3.1.3: This is tracked by the request context.

SessionInterface

The basic interface you have to implement in order to replace the default session interface which uses werkzeug’s securecookie implementation. The only methods you have to implement are open_session and save_session, the others have useful defaults which you don’t need to change. The session object returned by the open_session method has to provide a dictionary like interface plus the properties and methods from the SessionMixin. We recommend just subclassing a dict and adding that mixin:
class Session(dict, SessionMixin):
    pass
If open_session returns None Flask will call into make_null_session to create a session that acts as replacement if the session support cannot work because some requirement is not fulfilled. The default NullSession class that is created will complain that the secret key was not set. To replace the session interface on an application all you have to do is to assign flask.Flask.session_interface:
app = Flask(__name__)
app.session_interface = MySessionInterface()
Multiple requests with the same session may be sent and handled concurrently. When implementing a new session interface, consider whether reads or writes to the backing store must be synchronized. There is no guarantee on the order in which the session for each request is opened or saved, it will occur in the order that requests begin and end processing. Added in: 0.8

Class Attributes

null_session_class

make_null_session() will look here for the class that should be created when a null session is requested. Likewise the is_null_session() method will perform a typecheck against this type.
  • Type: type[NullSession]
  • Default: NullSession

pickle_based

A flag that indicates if the session interface is pickle based. This can be used by Flask extensions to make a decision in regards to how to deal with the session object.
  • Type: bool
  • Default: False
  • Added in: 0.10

Methods

make_null_session()

SessionInterface.make_null_session(app: Flask) -> NullSession
Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed. This creates an instance of null_session_class by default.
app
Flask
required
The Flask application instance

is_null_session()

SessionInterface.is_null_session(obj: object) -> bool
Checks if a given object is a null session. Null sessions are not asked to be saved. This checks if the object is an instance of null_session_class by default.
obj
object
required
The object to check
SessionInterface.get_cookie_name(app: Flask) -> str
The name of the session cookie. Uses app.config["SESSION_COOKIE_NAME"].
app
Flask
required
The Flask application instance
SessionInterface.get_cookie_domain(app: Flask) -> str | None
The value of the Domain parameter on the session cookie. If not set, browsers will only send the cookie to the exact domain it was set from. Otherwise, they will send it to any subdomain of the given value as well. Uses the SESSION_COOKIE_DOMAIN config. Changed in 2.3: Not set by default, does not fall back to SERVER_NAME.
app
Flask
required
The Flask application instance
SessionInterface.get_cookie_path(app: Flask) -> str
Returns the path for which the cookie should be valid. The default implementation uses the value from the SESSION_COOKIE_PATH config var if it’s set, and falls back to APPLICATION_ROOT or uses / if it’s None.
app
Flask
required
The Flask application instance
SessionInterface.get_cookie_httponly(app: Flask) -> bool
Returns True if the session cookie should be httponly. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var.
app
Flask
required
The Flask application instance
SessionInterface.get_cookie_secure(app: Flask) -> bool
Returns True if the cookie should be secure. This currently just returns the value of the SESSION_COOKIE_SECURE setting.
app
Flask
required
The Flask application instance
SessionInterface.get_cookie_samesite(app: Flask) -> str | None
Return 'Strict' or 'Lax' if the cookie should use the SameSite attribute. This currently just returns the value of the SESSION_COOKIE_SAMESITE setting.
app
Flask
required
The Flask application instance
SessionInterface.get_cookie_partitioned(app: Flask) -> bool
Returns True if the cookie should be partitioned. By default, uses the value of SESSION_COOKIE_PARTITIONED. Added in: 3.1
app
Flask
required
The Flask application instance

get_expiration_time()

SessionInterface.get_expiration_time(
    app: Flask,
    session: SessionMixin
) -> datetime | None
A helper method that returns an expiration date for the session or None if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application.
app
Flask
required
The Flask application instance
session
SessionMixin
required
The session object
SessionInterface.should_set_cookie(
    app: Flask,
    session: SessionMixin
) -> bool
Used by session backends to determine if a Set-Cookie header should be set for this session cookie for this response. If the session has been modified, the cookie is set. If the session is permanent and the SESSION_REFRESH_EACH_REQUEST config is true, the cookie is always set. This check is usually skipped if the session was deleted. Added in: 0.11
app
Flask
required
The Flask application instance
session
SessionMixin
required
The session object

open_session()

SessionInterface.open_session(
    app: Flask,
    request: Request
) -> SessionMixin | None
This is called at the beginning of each request, after pushing the request context, before matching the URL. This must return an object which implements a dictionary-like interface as well as the SessionMixin interface. This will return None to indicate that loading failed in some way that is not immediately an error. The request context will fall back to using make_null_session in this case.
app
Flask
required
The Flask application instance
request
Request
required
The request object

save_session()

SessionInterface.save_session(
    app: Flask,
    session: SessionMixin,
    response: Response
) -> None
This is called at the end of each request, after generating a response, before removing the request context. It is skipped if is_null_session returns True.
app
Flask
required
The Flask application instance
session
SessionMixin
required
The session object
response
Response
required
The response object

SecureCookieSessionInterface

The default session interface that stores sessions in signed cookies through the itsdangerous module.
class SecureCookieSessionInterface(SessionInterface)

Class Attributes

salt

The salt that should be applied on top of the secret key for the signing of cookie based sessions.
  • Type: str
  • Default: "cookie-session"

digest_method

The hash function to use for the signature.
  • Type: Callable
  • Default: sha1

key_derivation

The name of the itsdangerous supported key derivation.
  • Type: str
  • Default: "hmac"

serializer

A python serializer for the payload. The default is a compact JSON derived serializer with support for some extra Python types such as datetime objects or tuples.
  • Type: TaggedJSONSerializer

session_class

The session class to use.
  • Type: type[SecureCookieSession]
  • Default: SecureCookieSession

Methods

get_signing_serializer()

SecureCookieSessionInterface.get_signing_serializer(
    app: Flask
) -> URLSafeTimedSerializer | None
Returns a serializer for signing session cookies. Returns None if no secret key is configured.
app
Flask
required
The Flask application instance

Using Sessions

from flask import Flask, session

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

@app.route('/login', methods=['POST'])
def login():
    # Store data in session
    session['user_id'] = 123
    session['username'] = 'alice'
    session.permanent = True  # Use PERMANENT_SESSION_LIFETIME
    return 'Logged in'

@app.route('/profile')
def profile():
    # Access session data
    if 'user_id' not in session:
        return 'Not logged in', 401
    
    user_id = session.get('user_id')
    username = session.get('username')
    return f'User: {username} (ID: {user_id})'

@app.route('/logout')
def logout():
    # Clear session
    session.clear()
    return 'Logged out'

@app.route('/update-preferences', methods=['POST'])
def update_preferences():
    # Manually mark session as modified for nested dicts
    if 'preferences' not in session:
        session['preferences'] = {}
    
    session['preferences']['theme'] = 'dark'
    session.modified = True  # Required for nested modifications
    return 'Updated'

Custom Session Interface Example

from flask import Flask
from flask.sessions import SessionInterface, SessionMixin
import redis

class RedisSession(dict, SessionMixin):
    pass

class RedisSessionInterface(SessionInterface):
    def __init__(self, redis_client):
        self.redis = redis_client
    
    def open_session(self, app, request):
        session_id = request.cookies.get(app.config['SESSION_COOKIE_NAME'])
        if session_id:
            data = self.redis.get(f'session:{session_id}')
            if data:
                return RedisSession(json.loads(data))
        return RedisSession()
    
    def save_session(self, app, session, response):
        if not session:
            return
        
        session_id = generate_session_id()
        self.redis.set(
            f'session:{session_id}',
            json.dumps(dict(session)),
            ex=3600
        )
        response.set_cookie(
            app.config['SESSION_COOKIE_NAME'],
            session_id,
            httponly=True
        )

app = Flask(__name__)
redis_client = redis.Redis()
app.session_interface = RedisSessionInterface(redis_client)

Build docs developers (and LLMs) love