• key – the key (name) of the cookie to be set.
• value – the value of the cookie.
• max_age – should be a number of seconds, or None (default)
if the cookie should last only as long as the client’s browser
• expires – should be a datetime object or UNIX timestamp.
• domain – if you want to set a cross-domain cookie. For exam-
ple, domain=".example.com" will set a cookie that is readable
by the domain www.example.com, foo.example.com etc. Oth-
erwise, a cookie will only be readable by the domain that set
• path – limits the cookie to a given path, per default it will
span the whole domain.
If you have the Flask.secret_key set you can use sessions in Flask applications. A
session basically makes it possible to remember information from one request to an-
other. The way Flask does this is by using a signed cookie. So the user can look at the
session contents, but not modify it unless they know the secret key, so make sure to
set that to something complex and unguessable.
To access the current session you can use the session object:
The session object works pretty much like an ordinary dict, with the difference
that it keeps track on modiﬁcations.
This is a proxy. See Notes On Proxies for more information.
The following attributes are interesting:
True if the session is new, False otherwise.
True if the session object detected a modiﬁcation. Be advised that modiﬁca-
tions onmutable structures are notpicked up automatically, inthat situation
you have to explicitly set the attribute to True yourself. Here an example:
# this change is not picked up because a mutable object (here
# a list) is changed.
# so mark it as modified yourself
session.modified = True
Ifsetto Truethe session lives for permanent_session_lifetime seconds. The
default is 31 days. If set to False (which is the default) the session will be
deleted when the user closes the browser.
21.6 Session Interface
New in version 0.8.
The session interface provides a simple way toreplace the sessionimplementationthat
Flask is using.
The basicinterface you have to implement in order to replace the default session
interface which uses werkzeug’s securecookie implementation. The only meth-
ods 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 dic-
tionary like interface plus the properties and methods from the SessionMixin.
We recommend just subclassing a dict and adding that mixin:
class Session(dict, SessionMixin):
If open_session() returns NoneFlask will callintomake_null_session() to create
asession that acts as replacement if the session support cannot work because
some requirement is not fulﬁlled. 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
app = Flask(__name__)
app.session_interface = MySessionInterface()
New in version 0.8.
Helpful helper method that returns the cookie domain that should be used
for the session cookie if session cookies are used.
Returns True if the session cookie should be httponly. This currently just
returns the value of the SESSION_COOKIE_HTTPONLY conﬁg var.
Returns the path for which the cookie should be valid. The default imple-
mentation uses the value from the SESSION_COOKIE_PATH‘‘ conﬁg var if
it’s set, and falls back to APPLICATION_ROOT or uses / if it’s None.
Returns True if the cookie should be secure. This currently just returns the
value of the SESSION_COOKIE_SECURE setting.
Ahelper 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 conﬁgured on the application.
Checks if a given object is a null session. Null sessions are not asked to be
This checks if the object is an instance of null_session_class by default.
Creates a null session which acts as a replacement object if the real session
support could not be loaded due to a conﬁguration error. This mainly aids
the user experience because the job of the null session is to still support
lookup without complaining but modiﬁcations are answered witha helpful
error message of what failed.
This creates an instance of null_session_class by default.
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.
alias of NullSession
This method has to be implemented and must either return None in case
the loading failed because of a conﬁguration error or an instance of a ses-
sion object which implements a dictionary like interface + the methods and
attributes on SessionMixin.
pickle_based = False
Aﬂag that indicates if the session interface is pickle based. This can be used
by ﬂask extensions to make a decision in regards to how to deal with the
New in version 0.10.
save_session(app, session, response)
This is called for actual sessions returned by open_session() at the end of
the request. This is still called during a request context so if you absolutely
need access to the request you can do that.
The default session interface that stores sessions in signed cookies through the
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
salt = ‘cookie-session’
the salt that should be applied on top of the secret key for the signing of
cookie based sessions.
serializer = <ﬂask.sessions.TaggedJSONSerializer object>
Apython serializer for the payload. The default is a compact JSON derived
serializerwith support for some extra Python types suchas datetime objects
alias of SecureCookieSession
Baseclass for sessions based on signed cookies.
Class used to generate nicer errormessages if sessions are notavailable. Will still
allow read-only access to the empty session but fail on setting.
Expands a basic dictionary with an accessors that are expected by Flask exten-
sions and users for the session.
modified = True
for some backends this will always be True, but some backends will default
this to false and detect changes in the dictionary for as long as changes do
not happen on mutable structures in the session. The default mixin imple-
mentation just hardcodes True in.
new = False
some session backends can tell you if a session is new, but that is not nec-
essarily guaranteed. Use with caution. The default mixin implementation
just hardcodes False in.
this reﬂects the ’_permanent’ key in the dict.
flask.sessions.session_json_serializer = <ﬂask.sessions.TaggedJSONSerializer object>
Acustomized JSON serializer that supports a few extra types that we take for
granted when serializing (tuples, markup objects, datetime).
This object provides dumping and loading methods similar to simplejson but it
also tags certain builtin Python objects that commonly appear in sessions. Cur-
rently the following extended values are supported in the JSON it dumps:
The PERMANENT_SESSION_LIFETIME conﬁg key can also be an integer starting with Flask
0.8. Either catch this down yourself or use the permanent_session_lifetime attribute
on the app which converts the result to an integer automatically.
21.7 Test Client
Works like a regular Werkzeug test client but has some knowledge about how
Flask works to defer the cleanup of the request context stack to the end of a with
body when used in a with statement. For general information about how to use
this class refer towerkzeug.test.Client.
Basic usage is outlined in the Testing Flask Applications chapter.
When used incombinationwith a withstatement this opens a session trans-
action. This can be used to modify the session that the test client uses. Once
the with block is left the session is stored back.
with client.session_transaction() as session: session[’value’] = 42
Internally this is implemented by going through a temporary test request
context and since session handling could depend on request variables this
function accepts the same arguments as test_request_context() which are
directly passed through.
21.8 Application Globals
To share data that is valid for one request only from one function to another, a global
variable is not good enough because it would break in threaded environments. Flask
provides you with a special object that ensures it is only valid for the active request
and that will return different values for each request. In a nutshell: it does the right
thing, like it does for request and session.
Just store on this whatever you want. For example a database connection or the
user that is currently logged in.
Starting with Flask 0.10 this is stored on the application context and no longer
on the request context which means it becomes available if only the application
context is bound and not yet a request. This is especially useful when combined
with the Faking Resources and Context pattern for testing.
Documents you may be interested
Documents you may be interested