Flask-Session Documentation
repository·development·Indexed 19 days ago
https://github.com/pallets-eco/flask-sessionAn extension for Flask that provides server-side session support, allowing session data to be stored in external backends such as Redis, Memcached, MongoDB, SQLAlchemy, DynamoDB, and the local file system instead of client-side cookies.
What's inside Flask-Session
- Flask-Session is a Flask extension that enables server-side session management. Unlike default Flask sessions which are client-side, Flask-Session allows you to store session data in server-side storage, using a cookie only to hold a session identifier that links the client to their data on the server.
Understand the difference between permanent and non-permanent sessions
developmentFlask-Session inherits Flask's terminology for session cookies:
- Permanent session: A persistent cookie stored in the browser that is not deleted until it expires. It has a defined expiry.
- Non-permanent session: A session cookie (non-persistent) stored in the browser that is deleted when the browser or tab is closed. It has no expiry.
Note that the server can request the removal of either cookie type (e.g., during a logout process).
Retry behavior for SQL and other storage types
developmentFlask-Session handles retries differently depending on the storage backend used:
- SQL-based storage: Flask-Session automatically implements a retry mechanism with backoff. Upon encountering an exception, it will retry the operation up to 3 times. If the operation fails after these 3 retries, the exception is raised to the application.
- Other storage types (e.g., Redis): Retry logic is not managed by Flask-Session itself. Instead, retry logic must be configured directly within the storage client's setup. You should refer to the specific documentation for your storage client (like
redis-py) to implement retries.
Default session expiration behavior
developmentBy default, sessions managed by Flask-Session are permanent and have an expiration period of 31 days.Client-side vs Server-side sessions
developmentUnderstanding the difference between session storage models is critical for choosing the right approach:
- Client-side sessions: Data is stored directly in the client's browser via a cookie sent with every request/response. This is limited to small amounts of data (typically up to 4kB).
- Server-side sessions: Data is stored in server-side storage. The cookie sent to the client contains only a session identifier. This approach generally has no individual session size limitations, though developers should avoid using it as a primary database for large datasets.
Use CacheLib for indirect storage support
developmentFlask-Session supports storage and client libraries indirectly via
cachelib. To use this method, you must installcachelibitself along with the relevant client library for your chosen storage.Note:
cachelibcurrently usespickleas its default serializer, which may pose security risks if storage is compromised.| Storage | Client Library | | :--- | :--- | | File System | Not required | | Simple Memory | Not required | | UWSGI | uwsgi | | Redis | redis-py | | Memcached | pylibmc, python-memcached, libmc or google.appengine.api.memcache | | MongoDB | pymongo | | DynamoDB | boto3 |Quickstart: Set up Flask-Session with an application
developmentTo use Flask-Session, create your
flask.Flaskapplication, configure your desired session storage type (e.g.,'redis'), and then initialize theSessionobject by passing your application instance to it.Important: Do not use the
Sessioninstance directly to access or modify session data. TheSessionobject's purpose is to replace theflask.Flask.session_interface. You must always use the standardflask.sessionproxy to interact with the current session.from flask import Flask, session from flask_session import Session from redis import Redis app = Flask(__name__) SESSION_TYPE = 'redis' SESSION_REDIS = Redis(host='localhost', port=6379) app.config.from_object(__name__) Session(app) @app.route('/set/') def set_val(): session['key'] = 'value' return 'ok' @app.route('/get/') def get_val(): return session.get('key', 'not set')Install Flask-Session
developmentInstall Flask-Session using pip. You can specify extra dependencies for specific storage backends by including them in square brackets. For example, to use Redis, install with
flask-session[redis].$ pip install flask-session[redis]Use CacheLib as a session backend
developmentThe
FileSystemSessionhas been deprecated in favor of usingCacheLib. You can useCacheLibas a backend (for example, with a file system cache) by settingSESSION_TYPEto'cachelib'. This is useful for rapid development or testing.Required configuration keys:
SESSION_TYPE: Set to'cachelib'SESSION_SERIALIZATION_FORMAT: The format used for serialization (e.g.,'json')SESSION_CACHELIB: An instance of acachelibcache object.
from flask import Flask, session from flask_session import Session from cachelib.file import FileSystemCache app = Flask(__name__) SESSION_TYPE = 'cachelib' SESSION_SERIALIZATION_FORMAT = 'json' SESSION_CACHELIB = FileSystemCache(threshold=500, cache_dir="/sessions") app.config.from_object(__name__) Session(app)Install Flask-Session with a specific storage backend
developmentFlask-Session requires a storage backend and its corresponding client library to function. You can install these as optional dependencies using the bracket syntax:
pip install Flask-Session[<storage-option>].Recommended Storage: Redis is the recommended storage type as it provides the most complete support for Flask-Session features with minimal configuration.
Security Note: Flask-Session versions below 1.0.0 use
pickleas the default serializer. This may have security implications in production if your storage is compromised.pip install Flask-Session[<storage-option>]Mitigate session fixation by regenerating the session identifier
developmentSession fixation occurs when an attacker provides a known session identifier to a user to hijack their session later. To mitigate this, you should regenerate the session identifier immediately after a user successfully logs in.
In
flask-session, this is achieved by calling theregeneratemethod on theapp.session_interface. This method is provided by theflask_session.base.ServerSideSessionclass.@app.route('/login') def login(): # your login logic ... app.session_interface.regenerate(session) # your response ...Configure non-permanent sessions in Flask-Session
developmentFlask-Session is primarily designed for permanent sessions. To use non-permanent sessions (where the browser cookie is deleted when the browser or tab is closed), you must explicitly set
SESSION_PERMANENT=False.Warning: Using non-permanent sessions with server-side storage can lead to a large number of stale sessions on the server because the server cannot detect when a browser has been closed. To mitigate this, you should set
PERMANENT_SESSION_LIFETIMEto a short duration to ensure stale data is eventually cleaned up.# Example configuration for non-permanent sessions SESSION_PERMANENT = False PERMANENT_SESSION_LIFETIME = 3600 # Set to a short time to mitigate stale sessions