Session Interface โ
Changelog
New in version 0.8.
The session interface provides a simple way to replace the session implementation that Flask is using.
class flask.sessions.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):
passclass Session(dict, SessionMixin):
passIf 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()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.
Changelog
New in version 0.8.
get_cookie_domain(
app) โThe value of the
Domainparameter 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_DOMAINconfig.Changed in version 2.3: Not set by default, does not fall back to
SERVER_NAME.Parameters:
app (Flask)โ
Return type:
str | Noneget_cookie_httponly(
app) โReturns
Trueif the session cookie should be httponly. This currently just returns the value of theSESSION_COOKIE_HTTPONLYconfig var.Parameters:
app (Flask)โ
Return type:
boolget_cookie_name(
app) โThe name of the session cookie. Uses
app.config[โSESSION_COOKIE_NAMEโ].Parameters:
app (Flask)โ
Return type:
strget_cookie_path(
app) โReturns the path for which the cookie should be valid. The default implementation uses the value from the
SESSION_COOKIE_PATHconfig var if itโs set, and falls back toAPPLICATION_ROOTor uses/if itโsNone.Parameters:
app (Flask)โ
Return type:
strget_cookie_samesite(
app) โReturn
'Strict'or'Lax'if the cookie should use theSameSiteattribute. This currently just returns the value of theSESSION_COOKIE_SAMESITEsetting.Parameters:
app (Flask)โ
Return type:
strget_cookie_secure(
app) โReturns
Trueif the cookie should be secure. This currently just returns the value of theSESSION_COOKIE_SECUREsetting.Parameters:
app (Flask)โ
Return type:
boolget_expiration_time(
app, session) โA helper method that returns an expiration date for the session or
Noneif the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application.Parameters:
app (Flask)โsession (SessionMixin)โ
Return type:
datetime | Noneis_null_session(
obj) โ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_classby default.Parameters:
obj (object)โ
Return type:
boolmake_null_session(
app) โ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_classby default.Parameters:
app (Flask)โ
Return type:
NullSessionnull_session_class โ
make_null_session()will look here for the class that should be created when a null session is requested. Likewise theis_null_session()method will perform a typecheck against this type.alias of
NullSessionopen_session(
app, request) โ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
SessionMixininterface.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.Parameters:
app (Flask)โrequest (Request)โ
Return type:
SessionMixin | Nonepickle_based =
FalseโA flag that indicates if the session interface is pickle based. This can be used by
Flaskextensions to make a decision in regards to how to deal with the session object.Changelog
New in version 0.10.
save_session(
app, session, response) โ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()returnsTrue.Parameters:
app (Flask)โsession (SessionMixin)โresponse (Response)โ
Return type:
Noneshould_set_cookie(
app, session) โUsed by session backends to determine if a
Set-Cookieheader 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 theSESSION_REFRESH_EACH_REQUESTconfig is true, the cookie is always set.This check is usually skipped if the session was deleted.
Changelog
New in version 0.11.
Parameters:
app (Flask)โsession (SessionMixin)โ
Return type:
bool
class flask.sessions.SecureCookieSessionInterface โ
The default session interface that stores sessions in signed cookies through the itsdangerous module.
staticdigest_method(string=b'', *, usedforsecurity=True) โthe hash function to use for the signature. The default is sha1
key_derivation =
'hmac'โthe name of the itsdangerous supported key derivation. The default is
hmac.open_session(
app, request) โ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
SessionMixininterface.This will return
Noneto indicate that loading failed in some way that is not immediately an error. The request context will fall back to usingmake_null_session()in this case.Parameters:
app (Flask)โrequest (Request)โ
Return type:
SecureCookieSession | Nonesalt =
'cookie-session'โthe salt that should be applied on top of the secret key for the signing of cookie based sessions.
save_session(
app, session, response) โ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()returnsTrue.Parameters:
app (Flask)โsession (SessionMixin)โresponse (Response)โ
Return type:
Noneserializer =
<flask.json.tag.TaggedJSONSerializer object>โA python serializer for the payload. The default is a compact
JSONderived serializer with support for some extra Python types such as datetime objects or tuples.session_class โ
alias of
SecureCookieSession
class flask.sessions.SecureCookieSession(initial=None) โ
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.
Parameters:
initial (t.Any)โ
accessed =
Falseโheader, which allows caching proxies to cache different pages for different users.
get(
key, default=None) โReturn the value for key if key is in the dictionary, else default.
Parameters:
key (str)โdefault (Any | None)โ
Return type:
Anymodified =
Falseโ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 toTruemanually when modifying that data. The session cookie will only be written to the response if this isTrue.setdefault(
key, default=None) โInsert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
Parameters:
key (str) โdefault (Any | None)โ
Return type:
Any
class flask.sessions.NullSession(initial=None) โ
Class used to generate nicer error messages if sessions are not available. Will still allow read-only access to the empty session but fail on setting.
Parameters:
initial (t.Any)โ
clear() โ
NoneโRemove all items from D.
Parameters:
args (Any)โkwargs (Any)โ
Return type:
NoReturnpop(
k[, d]) โvโremove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a
KeyError.Parameters:
args (Any)โkwargs (Any)โ
Return type:
NoReturnpopitem(
*args, **kwargs) โRemove and return a
(key, value)pair as a 2-tuple.Pairs are returned in
LIFO(last-in, first-out) order. RaisesKeyErrorif the dict is empty.Parameters:
args (Any)โkwargs (Any)โ
Return type:
NoReturnsetdefault(
*args, **kwargs) โInsert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
Parameters:
args (Any)โkwargs (Any)โ
Return type:
NoReturnupdate(
[E, ]**F) โNoneโUpdate
Dfrom dict/iterableEandF.If
Eis present and has a.keys()method, then does:for k in E: D[k] = E[k] If Eis present and lacks a.keys()method, then does:for k, v in E: D[k] = vIn either case, this is followed by:for k in F: D[k] = F[k]Parameters:
args (Any)โkwargs (Any)โ
Return type:
NoReturn
class flask.sessions.SessionMixin โ
Expands a basic dictionary with session attributes.
accessed =
TrueโSome implementations can detect when session data is read or written and set this when that happens. The mixin default is hard coded to
True.modified =
TrueโSome implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to ยท.
propertypermanent:boolโThis reflects the
'_permanent'key in the dict.
Notice
The PERMANENT_SESSION_LIFETIME config can be an integer or timedelta. The permanent_session_lifetime attribute is always a timedelta.