YouTip LogoYouTip

Flask Session Interface Api

Flask Session Interface API

SessionInterface is the low-level abstraction of Session, allowing you to replace Flask’s default cookie-based storage with external storage systems such as Redis or databases.

To implement a custom session, simply inherit from SessionInterface and implement two methods.


SessionInterface Abstract Base Class

Attribute/Method Description
null_session_class The class used when Session is unavailable. Defaults to NullSession.
pickle_based bool, whether the Session uses pickle serialization. Defaults to False.
open_session(app, request) Reads Session data from the request. Returns a SessionMixin instance or None.
save_session(app, session, response) Saves Session data into the response.
make_null_session(app) Creates an empty Session (automatically called when open_session returns None).
is_null_session(obj) Checks whether the object is an instance of NullSession.

Cookie Option Methods

The following methods are used to retrieve various attributes of the Session cookie and can be overridden:

Method Description
get_cookie_name(app) Gets the cookie name. Defaults to reading the SESSION_COOKIE_NAME configuration.
get_cookie_domain(app) Gets the cookie domain. Defaults to reading the SESSION_COOKIE_DOMAIN configuration.
get_cookie_path(app) Gets the cookie path. Defaults to reading SESSION_COOKIE_PATH or APPLICATION_ROOT.
get_cookie_httponly(app) Gets the HttpOnly flag. Defaults to reading SESSION_COOKIE_HTTPONLY.
get_cookie_secure(app) Gets the Secure flag. Defaults to reading SESSION_COOKIE_SECURE.
get_cookie_samesite(app) Gets the SameSite value. Defaults to reading SESSION_COOKIE_SAMESITE.
get_cookie_partitioned(app) Gets the Partitioned flag. Defaults to reading SESSION_COOKIE_PARTITIONED (v3.1+).
get_expiration_time(app, session) Gets the Session expiration time. For permanent Sessions, returns now + lifetime.
should_set_cookie(app, session) Determines whether the cookie should be set. Returns True if the Session is modified or if it is permanent and SESSION_REFRESH_EACH_REQUEST is enabled.

Built-in Implementations

Class Description
SecureCookieSessionInterface The default implementation. Stores Session data using itsdangerous-signed cookies. key_derivation="hmac", digest_method=sha1.
SecureCookieSession A Session class based on CallbackDict. Detects modifications to top-level keys and automatically sets modified=True.
NullSession A placeholder Session used when SECRET_KEY is not set. Reads work normally, but modifications raise errors.
SessionMixin A mixin for Session classes. Provides permanent, new, modified, and accessed attributes.

Replacing the Default Session Implementation

Example

from flask import Flask

from flask.sessions import SessionInterface, SessionMixin

# Custom Session class

class MySession(dict, SessionMixin):

    pass

# Custom Session interface

class MySessionInterface(SessionInterface):

    def open_session(self, app, request):

        # Load Session from request
        user_id = request.headers.get("X-User-ID")
        if user_id:
            return MySession(user_id=user_id)
        return MySession()

    def save_session(self, app, session, response):

        # Save Session to response
        if "user_id" in session:
            response.headers = session

app = Flask(__name__)

# Replace default Session implementation
app.session_interface = MySessionInterface()
← Flask Test Cli Runner ApiFlask Response Api β†’