Flask-Session Documentation

repository·development·Indexed 19 days ago

https://github.com/pallets-eco/flask-session

An 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.

Tokens
13.8K
Snippets
40
Records
66
Agent score
67%

What's inside Flask-Session

  1. What is Flask-Session

    development
    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.
  2. Understand the difference between permanent and non-permanent sessions

    development

    Flask-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).

  3. Retry behavior for SQL and other storage types

    development

    Flask-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.
  4. Client-side vs Server-side sessions

    development

    Understanding 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.
  5. Use CacheLib for indirect storage support

    development

    Flask-Session supports storage and client libraries indirectly via cachelib. To use this method, you must install cachelib itself along with the relevant client library for your chosen storage.

    Note: cachelib currently uses pickle as 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 |
  6. Quickstart: Set up Flask-Session with an application

    development

    To use Flask-Session, create your flask.Flask application, configure your desired session storage type (e.g., 'redis'), and then initialize the Session object by passing your application instance to it.

    Important: Do not use the Session instance directly to access or modify session data. The Session object's purpose is to replace the flask.Flask.session_interface. You must always use the standard flask.session proxy 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')
  7. Use CacheLib as a session backend

    development

    The FileSystemSession has been deprecated in favor of using CacheLib. You can use CacheLib as a backend (for example, with a file system cache) by setting SESSION_TYPE to '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 a cachelib cache 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)
  8. Install Flask-Session with a specific storage backend

    development

    Flask-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 pickle as the default serializer. This may have security implications in production if your storage is compromised.

    pip install Flask-Session[<storage-option>]
  9. Mitigate session fixation by regenerating the session identifier

    development

    Session 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 the regenerate method on the app.session_interface. This method is provided by the flask_session.base.ServerSideSession class.

    @app.route('/login')
    def login():
        # your login logic ...
        app.session_interface.regenerate(session)
        # your response ...
  10. Configure non-permanent sessions in Flask-Session

    development

    Flask-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_LIFETIME to 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