### Initialize Flask App with Redis Session Backend Source: https://flask-session.readthedocs.io/en/latest/usage Demonstrates the quickstart method for initializing a Flask application with Flask-Session using Redis as the session backend. It shows app creation, configuration loading, session initialization, and basic route examples for setting and getting session data. Requires Flask and Flask-Session libraries. ```python 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(): session['key'] = 'value' return 'ok' @app.route('/get/') def get(): return session.get('key', 'not set') ``` -------------------------------- ### Install Flask-Session Source: https://flask-session.readthedocs.io/en/latest/installation Installs the Flask-Session package from PyPI using pip. This is the primary method for installing the library. ```bash $ pip install Flask-Session ``` -------------------------------- ### Install Flask-Session with Specific Storage Backend Source: https://flask-session.readthedocs.io/en/latest/installation Installs Flask-Session with support for a chosen storage backend. Replace '' with the desired backend name (e.g., 'memcached', 'mongodb'). ```bash pip install Flask-Session[] ``` -------------------------------- ### Install Flask-Session with Redis Support Source: https://flask-session.readthedocs.io/en/latest/installation Installs Flask-Session along with the necessary client library for Redis storage. This command installs Flask-Session and its Redis optional dependency. ```bash $ pip install Flask-Session[redis] ``` -------------------------------- ### Initialize Flask-Session with init_app (App Factory) Source: https://flask-session.readthedocs.io/en/latest/api Illustrates the alternate setup method using `init_app` for applications following the factory pattern. This allows for deferred initialization of the session interface. ```python from flask import Flask from flask_session import Session sess = Session() def create_app(): app = Flask(__name__) sess.init_app(app) return app ``` -------------------------------- ### Initialize Flask-Session with App Instance Source: https://flask-session.readthedocs.io/en/latest/api Demonstrates the typical setup for initializing Flask-Session by passing the Flask application instance directly to the Session constructor. This approach modifies the session_interface attribute of the Flask app. ```python from flask import Flask from flask_session import Session app = Flask(__name__) Session(app) ``` -------------------------------- ### Initialize Flask App with CacheLib FileSystemCache Backend Source: https://flask-session.readthedocs.io/en/latest/usage Demonstrates initializing Flask-Session using `CacheLib` with `FileSystemCache` as the backend. This setup is suitable for development or testing environments. It requires Flask, Flask-Session, and CacheLib libraries. Configuration includes session type and serialization format. ```python 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) ``` -------------------------------- ### Configure CacheLib Session Backend in Flask Source: https://flask-session.readthedocs.io/en/latest/config Demonstrates how to configure the CacheLib session backend for Flask-Session using a FileSystemCache. This example shows setting the cache directory and threshold for managing session data. Note that 'default_timeout' in CacheLib backends is overridden by 'PERMANENT_SESSION_LIFETIME'. ```python from flask import Flask from flask_session.sessions import CacheLibSessionInterface from cachelib import FileSystemCache app = Flask(__name__) # Configure CacheLib session backend app.config['SESSION_TYPE'] = 'cachelib' app.config['SESSION_CACHELIB'] = FileSystemCache(cache_dir='flask_session', threshold=500) # Ensure you have Flask-Session installed: pip install Flask-Session # And cachelib: pip install cachelib # Example usage (assuming session is configured elsewhere): # @app.route('/set_session') # def set_session(): # session['username'] = 'testuser' # return 'Session set' # @app.route('/get_session') # def get_session(): # return session.get('username', 'Not found') ``` -------------------------------- ### Configure Redis Session with Retries in Python Source: https://flask-session.readthedocs.io/en/latest/config This example shows how to configure a Redis client with retry logic for specific errors. It utilizes classes from the `redis` library such as `Retry` and `ExponentialBackoff`. This is particularly useful for SQL-based storage to handle transient connection issues. ```python 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]) ``` -------------------------------- ### MongoDB Session Interface Configuration Source: https://flask-session.readthedocs.io/en/latest/api Configures MongoDB as the backend for Flask sessions. This setup requires PyMongo and allows customization of connection details, session ID signing, permanence, length, serialization format, database name, and collection name. ```python from flask import Flask from flask_session import Session from pymongo import MongoClient app = Flask(__name__) # MongoDB session configuration app.config['SESSION_TYPE'] = 'mongodb' app.config['SESSION_MONGOALCHEMY_CLIENT'] = MongoClient('mongodb://localhost:27017/') app.config['SESSION_MONGOALCHEMY_DB'] = 'flask_session_db' app.config['SESSION_MONGOALCHEMY_COLLECTION'] = 'user_sessions' app.config['SESSION_USE_SIGNER'] = True app.config['SESSION_PERMANENT'] = True app.config['SESSION_SID_LENGTH'] = 32 app.config['SESSION_SERIALIZATION_FORMAT'] = 'msgpack' Session(app) @app.route('/') def index(): return 'Hello, World!' ``` -------------------------------- ### Configure Redis Session Backend in Flask Source: https://flask-session.readthedocs.io/en/latest/config This snippet demonstrates how to configure the Redis backend for Flask-Session. It requires the `redis` library to be installed. The configuration involves setting `SESSION_TYPE` to 'redis' and providing a `redis.Redis()` instance via `SESSION_REDIS` for custom connection details. ```python app.config['SESSION_TYPE'] = 'redis' app.config['SESSION_REDIS'] = Redis.from_url('redis://127.0.0.1:6379') ``` -------------------------------- ### Alternative Flask-Session Initialization with init_app Source: https://flask-session.readthedocs.io/en/latest/usage Shows an alternative way to initialize Flask-Session by creating a Session instance and then calling its init_app() method. This approach allows for delayed initialization of the session extension with the Flask application. It is a common pattern for initializing extensions in Flask applications. ```python from flask import Flask from flask_session import Session app = Flask(__name__) sess = Session() sess.init_app(app) ``` -------------------------------- ### Session Initialization Source: https://flask-session.readthedocs.io/en/latest/api Details on how to initialize the session management for a Flask application. ```APIDOC ## Session.init_app() ### Description Initializes the session extension with a Flask application. ### Method None (Class method or constructor argument) ### Endpoint N/A ### Parameters None directly for `init_app` itself, but requires a Flask app instance. ### Request Example ```python from flask import Flask from flask_session import Session app = Flask(__name__) Session(app) # Or app.config.from_object('config') and Session.init_app(app) ``` ### Response N/A ``` -------------------------------- ### Supported Session Backends Source: https://flask-session.readthedocs.io/en/latest/api Lists the various session storage backends supported by Flask-Session. ```APIDOC ## Supported Session Backends ### Description Flask-Session provides support for multiple server-side session storage solutions. ### Backends - **RedisSessionInterface**: For storing sessions in Redis. - **MemcachedSessionInterface**: For storing sessions in Memcached. - **FileSystemSessionInterface**: For storing sessions on the file system. - **CacheLibSessionInterface**: For storing sessions using cachelib. - **MongoDBSessionInterface**: For storing sessions in MongoDB. - **SqlAlchemySessionInterface**: For storing sessions using SQLAlchemy. - **DynamoDBSessionInterface**: For storing sessions in AWS DynamoDB. ### Configuration Example (Redis) ```python app.config['SESSION_TYPE'] = 'redis' app.config['SESSION_REDIS_HOST'] = 'localhost' app.config['SESSION_REDIS_PORT'] = 6379 app.config['SESSION_REDIS_DB'] = 0 ``` ``` -------------------------------- ### RedisSessionInterface Configuration Source: https://flask-session.readthedocs.io/en/latest/api Details the parameters for configuring the `RedisSessionInterface`, which uses Redis as the session storage backend. It covers options like client instance, key prefix, signer usage, permanence, session ID length, and serialization format. ```python from redis import Redis from flask_session.redis import RedisSessionInterface # Example configuration: r = Redis() redis_session_interface = RedisSessionInterface( client=r, key_prefix='my_app_session:', use_signer=True, permanent=False, sid_length=64, serialization_format='json' ) ``` -------------------------------- ### FileSystemSessionInterface Configuration Source: https://flask-session.readthedocs.io/en/latest/api Describes the parameters for configuring the `FileSystemSessionInterface`, which stores session data in the file system. Key options include the key prefix, signer usage, permanence, session ID length, serialization format, cache directory, threshold, and mode. ```python from flask_session.filesystem import FileSystemSessionInterface # Example configuration: fs_session_interface = FileSystemSessionInterface( key_prefix='my_app_session:', cache_dir='/tmp/flask_sessions', threshold=1000, mode=0o600 ) ``` -------------------------------- ### Redis Storage Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configure the Redis backend for session storage by providing a `redis.Redis` instance. ```APIDOC ## Storage Configuration: Redis ### `SESSION_REDIS` An instance of `redis.Redis` to be used for session storage. **Default:** An instance connected to `127.0.0.1:6379`. ``` -------------------------------- ### Memcached Storage Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configure the Memcached backend for session storage by providing a `memcache.Client` instance. ```APIDOC ## Storage Configuration: Memcached ### `SESSION_MEMCACHED` A `memcache.Client` instance to be used for session storage. **Default:** An instance connected to `127.0.0.1:6379`. ``` -------------------------------- ### CacheLib Storage Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configure the CacheLib backend for session storage, offering flexibility with various CacheLib backends. ```APIDOC ## Storage Configuration: CacheLib ### `SESSION_CACHELIB` Allows using any valid CacheLib backend. Configuration example: ```python app.config['SESSION_CACHELIB'] = FileSystemCache(cache_dir='flask_session', threshold=500) ``` **Important:** Any `default_timeout` set in CacheLib backends will be overridden by `PERMANENT_SESSION_LIFETIME`. **Default:** `FileSystemCache` in `./flask_session` directory. ``` -------------------------------- ### Flask-Session Specific Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configuration options specific to Flask-Session, including session type, permanence, signing, key prefix, and identifier length. ```APIDOC ## Flask-Session Configuration Values ### `SESSION_TYPE` Specifies the session interface to use. Built-in types include: - `redis`: RedisSessionInterface - `memcached`: MemcachedSessionInterface - `cachelib`: CacheLibSessionInterface - `mongodb`: MongoDBSessionInterface - `sqlalchemy`: SqlAlchemySessionInterface ### `SESSION_PERMANENT` Determines if sessions are permanent. **Default:** `True` ### `SESSION_KEY_PREFIX` Prefix added to all session keys for isolation. **Default:** `'session:'` ### `SESSION_ID_LENGTH` Length of the session identifier in bytes. **Default:** `32` ``` -------------------------------- ### Flask-Session Serialization Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configure the serialization format for session data. Supports 'msgpack' (default, more efficient) and 'json' (human-readable). Older versions used pickle, which is a security risk. ```APIDOC ## Serialization ### `SESSION_SERIALIZATION_FORMAT` Specifies the serialization format for session data. Recommended values are `'msgpack'` (default, more efficient) or `'json'` (human-readable). **Default:** `'msgpack'` **Note:** Versions below 1.0.0 used pickle, which is a security risk. Upgrade recommended. ``` -------------------------------- ### DynamoDB Session Interface Configuration Source: https://flask-session.readthedocs.io/en/latest/api Configures DynamoDB as the session backend, requiring boto3. Key parameters include the DynamoDB client, session ID signing, permanence, length, serialization format, and the DynamoDB table name for storing session data. ```python from flask import Flask from flask_session import Session import boto3 app = Flask(__name__) # DynamoDB session configuration app.config['SESSION_TYPE'] = 'dynamodb' app.config['SESSION_DYNAMODB_CLIENT'] = boto3.resource('dynamodb', region_name='us-east-1') app.config['SESSION_DYNAMODB_TABLE_NAME'] = 'my_flask_sessions' app.config['SESSION_USE_SIGNER'] = True app.config['SESSION_PERMANENT'] = True app.config['SESSION_SID_LENGTH'] = 32 app.config['SESSION_SERIALIZATION_FORMAT'] = 'msgpack' Session(app) @app.route('/') def index(): return 'Hello, World!' ``` -------------------------------- ### Server-Side Session Object Source: https://flask-session.readthedocs.io/en/latest/api Explains the attributes and properties of the server-side session object. ```APIDOC ## ServerSideSession Object ### Description Represents a server-side session with various attributes. ### Method N/A ### Endpoint N/A ### Attributes - **sid** (str) - The unique session ID. - **modified** (bool) - Flag indicating if the session has been modified. - **accessed** (bool) - Flag indicating if the session has been accessed. - **permanent** (bool) - Flag indicating if the session is permanent. ### Request Example ```python from flask import session # Accessing session attributes session_id = session.sid if session.modified: print("Session was modified") ``` ### Response N/A ``` -------------------------------- ### File System Storage Configuration (Deprecated) Source: https://flask-session.readthedocs.io/en/latest/config Configuration for the FileSystem session storage. Note: This interface is deprecated since version 0.7.0 and will be removed in 1.0.0. ```APIDOC ## Storage Configuration: FileSystem (Deprecated) ### `SESSION_FILE_DIR` Directory where session files are stored. **Default:** `./flask_session` directory. **Deprecated since version 0.7.0.** ### `SESSION_FILE_THRESHOLD` Maximum number of items in a session before deletion begins. **Default:** `500` **Deprecated since version 0.7.0.** ### `SESSION_FILE_MODE` File mode for session files. **Default:** `0600` **Deprecated since version 0.7.0.** ``` -------------------------------- ### MemcachedSessionInterface Configuration Source: https://flask-session.readthedocs.io/en/latest/api Outlines the configuration options for the `MemcachedSessionInterface`, which utilizes Memcached for session storage. Parameters include the client instance, key prefix, signer usage, permanence, session ID length, and serialization format. ```python from memcache import Client as MemcacheClient from flask_session.memcached import MemcachedSessionInterface # Example configuration: mc = MemcacheClient(['127.0.0.1:11211']) memcached_session_interface = MemcachedSessionInterface( client=mc, key_prefix='my_app_session:', use_signer=False, permanent=True, sid_length=32, serialization_format='pickle' ) ``` -------------------------------- ### Session Interface Methods Source: https://flask-session.readthedocs.io/en/latest/api Details on methods provided by session interfaces for session regeneration. ```APIDOC ## ServerSideSessionInterface.regenerate() ### Description Regenerates the session ID, invalidating the old session and creating a new one. ### Method `regenerate()` ### Endpoint N/A ### Parameters None ### Request Example ```python from flask_session import ServerSideSessionInterface # Assuming 'session_interface' is an instance of ServerSideSessionInterface or a subclass session_interface.regenerate() ``` ### Response N/A ``` -------------------------------- ### SQLAlchemy Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configure Flask-Session to use SQLAlchemy for session storage. This involves providing a SQLAlchemy instance and optionally specifying table, sequence, schema, and bind key names. ```APIDOC ## SQLAlchemy Session Configuration ### Description Configure Flask-Session to use SQLAlchemy as the session storage backend. Requires Flask-SQLAlchemy version 3.0 or higher. ### Parameters #### Environment Variables / App Configuration - **SESSION_SQLALCHEMY** (flask_sqlalchemy.SQLAlchemy) - Required - A `flask_sqlalchemy.SQLAlchemy` instance with `SQLALCHEMY_DATABASE_URI` configured. - **SESSION_SQLALCHEMY_TABLE** (string) - Optional - The name of the SQL table for sessions. Defaults to `'sessions'`. - **SESSION_SQLALCHEMY_SEQUENCE** (string) - Optional - The name of the sequence for the primary key. Defaults to `None`. - **SESSION_SQLALCHEMY_SCHEMA** (string) - Optional - The name of the schema to use. Defaults to `None`. - **SESSION_SQLALCHEMY_BIND_KEY** (string) - Optional - The name of the bind key to use. Defaults to `None`. ### Request Example (Configuration) ```python from flask import Flask from flask_session import Session from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@host:port/database' session_manager = SQLAlchemy(app) app.config['SESSION_TYPE'] = 'sqlalchemy' app.config['SESSION_SQLALCHEMY'] = session_manager app.config['SESSION_SQLALCHEMY_TABLE'] = 'app_sessions' Session(app) ``` ### Response Example (Conceptual) This configuration does not directly involve API request/response cycles but affects how session data is stored and retrieved. ``` -------------------------------- ### Directly Set RedisSessionInterface in Flask Source: https://flask-session.readthedocs.io/en/latest/usage Illustrates how to directly set the session interface for a Flask application by instantiating and assigning `RedisSessionInterface` to `app.session_interface`. This method bypasses the `Session` extension object and directly configures the session handling mechanism. It requires Flask, Flask-Session, and Redis libraries. ```python from flask import Flask, session from flask_session.redis import RedisSessionInterface from redis import Redis app = Flask(__name__) redis = Redis(host='localhost', port=6379) app.session_interface = RedisSessionInterface(client=redis) ``` -------------------------------- ### DynamoDB Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configure Flask-Session to use DynamoDB as the session storage backend. This involves providing a boto3 resource instance and specifying the table name. ```APIDOC ## DynamoDB Session Configuration ### Description Configure Flask-Session to use DynamoDB as the session storage backend. ### Parameters #### Environment Variables / App Configuration - **SESSION_DYNAMODB** (boto3.resource) - Required - A `boto3.resource` instance. Defaults to an instance connected to `'localhost:8000'`. - **SESSION_DYNAMODB_TABLE_NAME** (string) - Optional - The name of the DynamoDB table for sessions. Defaults to `'Sessions'`. ### Request Example (Configuration) ```python from flask import Flask from flask_session import Session import boto3 app = Flask(__name__) # DynamoDB Configuration db = boto3.resource('dynamodb', region_name='us-east-1', endpoint_url='http://localhost:8000') app.config['SESSION_TYPE'] = 'dynamodb' app.config['SESSION_DYNAMODB'] = db app.config['SESSION_DYNAMODB_TABLE_NAME'] = 'flask_session_table' Session(app) ``` ### Response Example (Conceptual) This configuration does not directly involve API request/response cycles but affects how session data is stored and retrieved. ``` -------------------------------- ### SQLAlchemy Session Interface Configuration Source: https://flask-session.readthedocs.io/en/latest/api Configures Flask-SQLAlchemy as the session storage. It supports defining the table name, sequence, schema, bind key, and session cleanup frequency, alongside standard session parameters like signing, permanence, ID length, and serialization format. ```python from flask import Flask from flask_session import Session from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sessions.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False session_db = SQLAlchemy(app) # SQLAlchemy session configuration app.config['SESSION_TYPE'] = 'sqlalchemy' app.config['SESSION_SQLALCHEMY_CLIENT'] = session_db app.config['SESSION_SQLALCHEMY_TABLE'] = 'flask_session_data' app.config['SESSION_USE_SIGNER'] = False app.config['SESSION_PERMANENT'] = True app.config['SESSION_SID_LENGTH'] = 32 app.config['SESSION_SERIALIZATION_FORMAT'] = 'json' app.config['SESSION_SQLALCHEMY_CLEANUP_N_REQUESTS'] = 100 Session(app) @app.route('/') def index(): return 'Hello, World!' ``` -------------------------------- ### Handle Redis Errors with Flask Error Handler Source: https://flask-session.readthedocs.io/en/latest/config This Python snippet illustrates how to set up a Flask error handler for `RedisError`. It logs the specific Redis error encountered and returns a user-friendly message to the client. This approach improves error reporting and user experience when Redis-related issues occur. ```python @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 ``` -------------------------------- ### MongoDB Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configure Flask-Session to use MongoDB as the session storage backend. This includes specifying the MongoDB client instance, database name, and collection name. ```APIDOC ## MongoDB Session Configuration ### Description Configure Flask-Session to use MongoDB as the session storage backend. ### Parameters #### Environment Variables / App Configuration - **SESSION_MONGODB** (pymongo.MongoClient) - Required - A `pymongo.MongoClient` instance. Defaults to an instance connected to `127.0.0.1:27017`. - **SESSION_MONGODB_DB** (string) - Optional - The MongoDB database name. Defaults to `'flask_session'`. - **SESSION_MONGODB_COLLECT** (string) - Optional - The MongoDB collection name. Defaults to `'sessions'`. ### Request Example (Configuration) ```python from flask import Flask from flask_session import Session from pymongo import MongoClient app = Flask(__name__) # MongoDB Configuration client = MongoClient('mongodb://localhost:27017/') app.config['SESSION_TYPE'] = 'mongodb' app.config['SESSION_MONGODB'] = client app.config['SESSION_MONGODB_DB'] = 'my_app_db' app.config['SESSION_MONGODB_COLLECT'] = 'user_sessions' Session(app) ``` ### Response Example (Conceptual) This configuration does not directly involve API request/response cycles but affects how session data is stored and retrieved. ``` -------------------------------- ### Session Cleanup Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configure the frequency of automatic session cleanup for non-TTL backends. This setting is only applicable when session expiration is not managed by TTL. ```APIDOC ## Session Cleanup Configuration ### Description Configure the automatic session cleanup frequency for non-TTL backends. This setting determines how often Flask-Session will remove expired sessions. ### Parameters #### Environment Variables / App Configuration - **SESSION_CLEANUP_N_REQUESTS** (integer | None) - Optional - The average number of requests after which Flask-Session will perform a session cleanup. If `None`, automatic cleanup is disabled, and `flask session_cleanup` command should be used. Defaults to `None`. ### Request Example (Configuration) ```python from flask import Flask from flask_session import Session app = Flask(__name__) app.config['SESSION_TYPE'] = 'filesystem' # Example for a non-TTL backend app.config['SESSION_CLEANUP_N_REQUESTS'] = 1000 # Perform cleanup every 1000 requests Session(app) ``` ### Response Example (Conceptual) This configuration impacts background session management and does not directly correspond to typical API request/response patterns. ``` -------------------------------- ### Cachelib Session Interface Configuration Source: https://flask-session.readthedocs.io/en/latest/api Configures the Cachelib backend for Flask sessions. It allows specifying whether to sign session cookies, use permanent sessions, set the session ID length, choose a serialization format, and define the cache directory and file mode. ```python from flask import Flask from flask_session import Session app = Flask(__name__) # Cachelib session configuration app.config['SESSION_TYPE'] = 'cachelib' app.config['SESSION_CACHELIB_CLIENT'] = cachelib.SimpleCache() app.config['SESSION_USE_SIGNER'] = True app.config['SESSION_PERMANENT'] = False app.config['SESSION_SID_LENGTH'] = 20 app.config['SESSION_SERIALIZATION_FORMAT'] = 'json' app.config['SESSION_CACHELIB_CACHE_DIR'] = '/path/to/cache' app.config['SESSION_CACHELIB_THRESHOLD'] = 500 app.config['SESSION_CACHELIB_MODE'] = 0o644 Session(app) @app.route('/') def index(): return 'Hello, World!' ``` -------------------------------- ### Scheduled Session Cleanup Command Source: https://flask-session.readthedocs.io/en/latest/config This command is used to manually clean up expired sessions from the database. It is intended to be run regularly via a cron job or scheduler. This method is crucial for SQL-based storage engines where automatic cleanup is not provided. ```bash flask session_cleanup ``` -------------------------------- ### ServerSideSession Base Class Attributes Source: https://flask-session.readthedocs.io/en/latest/api Explains key attributes of the `ServerSideSession` base class, which is accessible via `flask.session`. These attributes control session ID generation, modification tracking, and permanence. ```python from flask_session.base import ServerSideSession # Example usage (conceptual): session: ServerSideSession = flask.session # Accessing attributes: # session.sid # session.modified # session.accessed # session.permanent ``` -------------------------------- ### Flask Session Cookie Configuration Source: https://flask-session.readthedocs.io/en/latest/config Configuration values from Flask that affect the session cookie set on the browser. These should be configured in your Flask app before initializing Flask-Session. ```APIDOC ## Relevant Flask Configuration Values These Flask configuration values influence the session cookie: - **`SESSION_COOKIE_NAME`**: Name of the session cookie. - **`SESSION_COOKIE_DOMAIN`**: Domain for the session cookie. - **`SESSION_COOKIE_PATH`**: Path for the session cookie. - **`SESSION_COOKIE_HTTPONLY`**: Whether the cookie is HTTP only. - **`SESSION_COOKIE_SECURE`**: Whether the cookie is secure (HTTPS). - **`SESSION_COOKIE_SAMESITE`**: SameSite attribute for the cookie. - **`SESSION_REFRESH_EACH_REQUEST`**: Whether to refresh the session on each request. - **`PERMANENT_SESSION_LIFETIME`**: Lifetime of a permanent session, also affects server-side expiration. ``` -------------------------------- ### Mitigate Session Fixation with Flask-Session Regenerate Source: https://flask-session.readthedocs.io/en/latest/security Demonstrates how to regenerate the session identifier when a user logs in to prevent session fixation attacks. This is achieved by calling the `regenerate` method on the Flask app's session interface. Ensure your Flask application is configured to use Flask-Session. ```python from flask import Flask, session app = Flask(__name__) @app.route('/login') def login(): # your login logic ... app.session_interface.regenerate(session) # your response ... ``` -------------------------------- ### ServerSideSessionInterface Regenerate Session ID Source: https://flask-session.readthedocs.io/en/latest/api Shows how to regenerate the session ID for a given session object. This functionality is accessed through the `regenerate` method of the session interface. ```python from flask_session.base import ServerSideSession, ServerSideSessionInterface # Example usage (conceptual): session_interface: ServerSideSessionInterface = flask.session_interface some_session: ServerSideSession = flask.session session_interface.regenerate(some_session) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.