Configuration#
Example#
Here is an example of how to configure a redis backend:
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = Redis.from_url('redis://127.0.0.1:6379')
We are not supplying something like SESSION_REDIS_HOST
and
SESSION_REDIS_PORT
, instead you should configure SESSION_REDIS
to your own redis.Redis()
instance.
This gives you more flexibility, such as using the same instance for cache purposes too, then you do not need to keep
two instances in the same process.
If you do not set SESSION_REDIS
, Flask-Session will assume you are developing locally and create a
redis.Redis()
instance for you. It is expected you supply an instance of
redis.Redis()
in production.
Note
By default, sessions in Flask-Session are permanent with an expiration of 31 days.
Non-permanent sessions#
Caution
Flask-session is primarily designed to be used with permanent sessions. If you want to use non-permanent sessions, you must set SESSION_PERMANENT=False
and be aware of significant limitations.
Flask terminology regarding it’s built-in client-side session is inherited by Flask-Session:
Permanent session: A cookie is stored in the browser and not deleted until it expires (has expiry). Also known as a persistent cookie.
Non-permanent session: A cookie is stored in the browser and is deleted when the browser or tab is closed (no expiry). Also known as a session cookie or non-persistent cookie.
Either cookie can be removed earlier if requested by the server, for example during logout.
In the case of non-permanent server-side sessions, the server has no way to know when the browser is closed and it’s session cookie removed as a result, so it cannot confidently know when to delete the stored session data linked to that browser. This can lead to a large number of stale sessions being stored on the server.
To mitigate this somewhat, Flask-Session always sets server-side expiration time using PERMANENT_SESSION_LIFETIME
. As such, PERMANENT_SESSION_LIFETIME
can be set to a very short time to further mitigate this.
Scheduled session cleanup#
Important
In the case of SQLAlchemy
, expired sessions are not automatically deleted from the database. You must use one of the following scheduled cleanup methods.
Run the the following command regularly with a cron job or scheduler such as Heroku Scheduler to clean up expired sessions. This is the recommended way to clean up expired sessions.
flask session_cleanup
Alternatively, set the configuration variable SESSION_CLEANUP_N_REQUESTS
to the average number of requests after which the cleanup should be performed. This is less desirable than using the scheduled app command cleanup as it may slow down some requests but may be useful for small applications or rapid development.
This is not required for the Redis
, Memecached
, Filesystem
, Mongodb
storage engines, as they support time-to-live for records.
Retries#
Only for SQL based storage, upon an exception, Flask-Session will retry with backoff up to 3 times. If the operation still fails after 3 retries, the exception will be raised.
For other storage types, the retry logic is either included or can be configured in the client setup. Refer to the relevant client documentation for more information.
Redis example with retries on certain errors:
from redis.backoff import ExponentialBackoff
from redis.retry import Retry
from redis.client import Redis
from redis.exceptions import (
BusyLoadingError,
ConnectionError,
TimeoutError
)
...
retry = Retry(ExponentialBackoff(), 3)
SESSION_REDIS = Redis(host='localhost', port=6379, retry=retry, retry_on_error=[BusyLoadingError, ConnectionError, TimeoutError])
Logging#
If you want to show user more helpful error messages, you can use Flask’s error handling. For example:
@app.errorhandler(RedisError)
def handle_redis_error(error):
app.logger.error(f"Redis error encountered: {error}")
return "A problem occurred with our Redis service. Please try again later.", 500
Serialization#
Warning
Flask-session versions below 1.0.0 use pickle serialization (or fallback) for session storage. While not a direct vulnerability, it is a potential security risk. If you are using a version below 1.0.0, it is recommended to upgrade to the latest version as soon as it’s available.
From 0.7.0 the serializer is msgspec, which is configurable using SESSION_SERIALIZATION_FORMAT
. The default format is 'msgpack'
which has 30% storage reduction compared to 'json'
. The 'json'
format may be helpful for debugging, easier viewing or compatibility. Switching between the two should be seamless, even for existing sessions.
All sessions that are accessed or modified while using 0.7.0 will convert to a msgspec format. Once using 1.0.0, any sessions that are still in pickle format will be cleared upon access.
The msgspec library has speed and memory advantages over other libraries. However, if you want to use a different library (such as pickle or orjson), you can override the session_interface.serializer
.
Relevant Flask configuration values#
The following configuration values are from Flask itself that are relate to the Flask session cookie set on the browser. Flask-Session loads these values from your Flask application config, so you should configure your app first before you pass it to Flask-Session.
These values cannot be modified after the init_app
was applied so make sure to not
modify them at runtime.
Note
PERMANENT_SESSION_LIFETIME
is also used to set the expiration time of the session data on the server side, regardless of SESSION_PERMANENT
.
Flask-Session configuration values#
These are specific to Flask-Session.
- SESSION_TYPE#
Specifies which type of session interface to use. Built-in session types:
redis: RedisSessionInterface
memcached: MemcachedSessionInterface
filesystem: FileSystemSessionInterface (Deprecated in 0.7.0, will be removed in 1.0.0 in favor of CacheLibSessionInterface)
cachelib: CacheLibSessionInterface
mongodb: MongoDBSessionInterface
sqlalchemy: SqlAlchemySessionInterface
- SESSION_PERMANENT#
Whether use permanent session or not.
Default:
True
- SESSION_USE_SIGNER#
Whether sign the session cookie sid or not, if set to
True
, you have to setflask.Flask.secret_key
.Note
This feature is historical and generally only relevant if you are using client-side sessions ie. not Flask-Session. SESSION_ID_LENGTH provides the relevant entropy for session identifiers.
Default:
False
Deprecated since version 0.7.0.
- SESSION_KEY_PREFIX#
A prefix that is added before all session keys. This makes it easier to use the same backend storage server for different apps.
Default:
'session:'
- SESSION_ID_LENGTH#
The length of the session identifier in bytes (of entropy).
Default:
32
New in version 0.6.0.
- SESSION_SERIALIZATION_FORMAT#
The serialization format to use. Can be ‘msgpack’` or ‘json’. Set to ‘msgpack’` for a more efficient serialization format. Set to ‘json’` for a human-readable format.
Default:
'msgpack'
New in version 0.7.0.
Deprecated since version 0.7.0: SESSION_USE_SIGNER
New in version 0.7.0: SESSION_SERIALIZATION_FORMAT
New in version 0.6.0: SESSION_ID_LENGTH
Storage configuration#
Redis#
- SESSION_REDIS#
A
redis.Redis
instance.Default: Instance connected to
127.0.0.1:6379
Memcached#
- SESSION_MEMCACHED#
A
memcache.Client
instance.Default: Instance connected to
127.0.0.1:6379
FileSystem#
- SESSION_FILE_DIR#
The directory where session files are stored.
Default:
flask_session
directory under current working directory.Deprecated since version 0.7.0.
- SESSION_FILE_THRESHOLD#
The maximum number of items the session stores before it starts deleting some.
Default:
500
Deprecated since version 0.7.0.
- SESSION_FILE_MODE#
The file mode wanted for the session files.
Default:
0600
Deprecated since version 0.7.0.
CacheLib#
- SESSION_CACHELIB#
Any valid cachelib backend. This allows you maximum flexibility in choosing the cache backend and it’s configuration.
The following would set a cache directory called “flask_session” and a threshold of 500 items before it starts deleting some.
app.config['SESSION_CACHELIB'] = FileSystemCache(cache_dir='flask_session', threshold=500)
Important
A
default_timeout
set in any of theCacheLib
backends will be overrode by thePERMANENT_SESSION_LIFETIME
when each stored session’s expiry is set.Default:
FileSystemCache
in./flask_session
directory.
MongoDB#
- SESSION_MONGODB#
A
pymongo.MongoClient
instance.Default: Instance connected to
127.0.0.1:27017
- SESSION_MONGODB_DB#
The MongoDB database you want to use.
Default:
'flask_session'
- SESSION_MONGODB_COLLECT#
The MongoDB collection you want to use.
Default:
'sessions'
SqlAlchemy#
- SESSION_SQLALCHEMY#
A
flask_sqlalchemy.SQLAlchemy
instance whose database connection URI is configured using theSQLALCHEMY_DATABASE_URI
parameter.Must be set in flask_sqlalchemy version 3.0 or higher.
- SESSION_SQLALCHEMY_TABLE#
The name of the SQL table you want to use.
Default:
'sessions'
- SESSION_SQLALCHEMY_SEQUENCE#
The name of the sequence you want to use for the primary key.
Default:
None
- SESSION_SQLALCHEMY_SCHEMA#
The name of the schema you want to use.
Default:
None
- SESSION_SQLALCHEMY_BIND_KEY#
The name of the bind key you want to use.
Default:
None
- SESSION_CLEANUP_N_REQUESTS#
Only applicable to non-TTL backends.
The average number of requests after which Flask-Session will perform a session cleanup. This involves removing all session data that is older than
PERMANENT_SESSION_LIFETIME
. Using the app commandflask session_cleanup
instead is preferable.Default:
None
Dynamodb#
- SESSION_DYNAMODB#
A
boto3.resource
instance.Default: Instance connected to
'localhost:8000'
- SESSION_DYNAMODB_TABLE_NAME#
The name of the table you want to use.
Default:
'Sessions'
Deprecated since version 0.7.0: SESSION_FILE_DIR
, SESSION_FILE_THRESHOLD
, SESSION_FILE_MODE
. Use SESSION_CACHELIB
instead.
New in version 0.7.0: SESSION_CLEANUP_N_REQUESTS
New in version 0.6.0: SESSION_SQLALCHEMY_BIND_KEY
, SESSION_SQLALCHEMY_SCHEMA
, SESSION_SQLALCHEMY_SEQUENCE