### Quickstart: Initialize Flask-Session with Redis Source: https://github.com/pallets-eco/flask-session/blob/development/docs/usage.md Demonstrates the basic setup of Flask-Session with a Redis backend. It involves creating a Flask app, configuring session type and Redis connection details, and then initializing the Session object. Accessing and modifying session data is shown using `flask.session`. ```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') ``` -------------------------------- ### Run Python examples with Rye Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Executes Python example scripts using the Rye-managed Python environment. This allows developers to test specific functionalities or examples within the project. ```bash rye run python examples/hello.py ``` -------------------------------- ### Install Flask-Session with Redis Support Source: https://github.com/pallets-eco/flask-session/blob/development/README.md Installs the Flask-Session package along with the Redis client library, enabling Redis as the session storage backend. Ensure Redis server is running and accessible. ```shell pip install flask-session[redis] ``` -------------------------------- ### Install development dependencies with pip Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Installs project dependencies, including development and documentation requirements, from the specified requirement files. Ensures all necessary packages are available for development. ```bash pip install -r requirements/dev.txt pip install -r requirements/docs.in ``` -------------------------------- ### Synchronize Dependencies with Rye Source: https://github.com/pallets-eco/flask-session/blob/development/CONTRIBUTING.rst Synchronizes project dependencies using the 'rye' package manager. This command ensures that the local environment matches the project's defined dependencies. ```bash rye sync ``` -------------------------------- ### Set up Python virtual environment with pip Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Creates and activates a Python virtual environment using the venv module. This isolates project dependencies and ensures a clean development setup. ```bash python -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Run Flask-Session Tests with Pytest Source: https://github.com/pallets-eco/flask-session/blob/development/CONTRIBUTING.rst Executes the project's tests using pytest. This ensures the project functions as expected. Requires Docker containers to be running. ```bash pytest tests ``` -------------------------------- ### Manage Docker containers for testing Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Starts and stops Docker containers required for testing the Flask-Session project. This simplifies the setup and teardown of the testing environment. ```bash docker-compose up -d docker-compose down ``` -------------------------------- ### Set Python Version with Rye Source: https://github.com/pallets-eco/flask-session/blob/development/CONTRIBUTING.rst Pins the Python version for the project to 3.11 using the 'rye' package manager. This ensures consistent Python environments. ```bash rye pin 3.11 ``` -------------------------------- ### Filesystem Session Backend for Flask Source: https://context7.com/pallets-eco/flask-session/llms.txt Implements session storage using the local filesystem. It is suitable for single-server deployments and does not require external services. This example stores and retrieves temporary data. ```python from flask import Flask, session from flask_session import Session app = Flask(__name__) app.config.update( SESSION_TYPE='filesystem', SESSION_FILE_DIR='/tmp/flask_sessions', SESSION_FILE_THRESHOLD=500, # Max number of session files SESSION_FILE_MODE=0o600, # File permissions SESSION_KEY_PREFIX='session:', SESSION_PERMANENT=True ) Session(app) @app.route('/temp-data') def store_temp_data(): session['temp_value'] = 'temporary_data' return 'Stored in filesystem' @app.route('/get-temp-data') def get_temp_data(): return {'value': session.get('temp_value', 'not found')} if __name__ == '__main__': app.run() ``` -------------------------------- ### Set up Python environment with Rye Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Manages the Python toolchain and project dependencies using the Rye package manager. It pins a specific Python version and synchronizes installed packages. ```bash rye pin 3.11 rye sync ``` -------------------------------- ### Initialize Flask-Session using Application Factory Pattern Source: https://github.com/pallets-eco/flask-session/blob/development/docs/api.md Illustrates the alternate setup method using an application factory pattern. An instance of Session is created first, and then its `init_app` method is called with the Flask application object, which is useful for more complex application structures. ```python from flask import Flask from flask_session import Session sess = Session() def create_app(): app = Flask(__name__) sess.init_app(app) return app ``` -------------------------------- ### Run Specific Flask-Session Test File Source: https://github.com/pallets-eco/flask-session/blob/development/CONTRIBUTING.rst Executes a specific test file within the Flask-Session project using pytest. This is useful for focused testing. ```bash pytest tests/test_basic.py ``` -------------------------------- ### Alternative Initialization: `init_app()` for Flask-Session Source: https://github.com/pallets-eco/flask-session/blob/development/docs/usage.md Shows an alternative way to initialize Flask-Session using the `init_app()` method. This is useful when the Session object is created before the Flask application instance. ```python from flask_session import Session # ... Flask app setup ... sess = Session() sess.init_app(app) ``` -------------------------------- ### Configure Flask-Session Redis Backend Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_example.md Configures Flask-Session to use Redis for session storage by setting the SESSION_TYPE and providing a custom redis.Redis() instance. ```python from redis import Redis app.config['SESSION_TYPE'] = 'redis' app.config['SESSION_REDIS'] = Redis.from_url('redis://127.0.0.1:6379') ``` -------------------------------- ### Flask App with MongoDB Session Backend Source: https://context7.com/pallets-eco/flask-session/llms.txt Demonstrates setting up Flask-Session to use MongoDB as the server-side session storage. This example shows how to initialize a MongoClient and configure Flask-Session with MongoDB-specific settings like database name and collection name. It includes routes for managing a shopping cart within the session. ```python from flask import Flask, session from flask_session import Session from pymongo import MongoClient app = Flask(__name__) # Create MongoDB client mongo_client = MongoClient('mongodb://localhost:27017/') app.config.update( SESSION_TYPE='mongodb', SESSION_MONGODB=mongo_client, SESSION_MONGODB_DB='myapp_db', SESSION_MONGODB_COLLECT='sessions', SESSION_KEY_PREFIX='session:', SESSION_PERMANENT=True ) Session(app) @app.route('/shopping-cart/add/') def add_to_cart(item): cart = session.get('cart', []) cart.append(item) session['cart'] = cart session.modified = True # Mark as modified for nested data return f'Added {item} to cart. Total items: {len(cart)}' @app.route('/shopping-cart/view') def view_cart(): cart = session.get('cart', []) return {'items': cart, 'count': len(cart)} @app.route('/shopping-cart/clear') def clear_cart(): session.pop('cart', None) return 'Cart cleared' if __name__ == '__main__': app.run() ``` -------------------------------- ### Install Flask-Session in editable mode with pip Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Installs the Flask-Session package in editable mode. This allows for changes in the source code to be reflected immediately without reinstallation, facilitating rapid development. ```bash pip install -e . ``` -------------------------------- ### Using CacheLib as a Session Backend with File System Cache Source: https://github.com/pallets-eco/flask-session/blob/development/docs/usage.md Demonstrates configuring Flask-Session to use CacheLib with a file system cache. This approach is suitable for development or testing purposes and requires specifying the session type and CacheLib configuration. ```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) ``` -------------------------------- ### Flask App Factory Pattern with Session Initialization Source: https://context7.com/pallets-eco/flask-session/llms.txt Illustrates integrating Flask-Session within the Flask application factory pattern. The Session extension is initialized using `sess.init_app(app)`, allowing for flexible configuration and route definitions within the factory function. It includes examples of setting session data. ```python from flask import Flask, session from flask_session import Session sess = Session() def create_app(): app = Flask(__name__) app.config.update( SESSION_TYPE='redis', SESSION_PERMANENT=True, SESSION_USE_SIGNER=False, SESSION_KEY_PREFIX='myapp:', SESSION_SERIALIZATION_FORMAT='json', SECRET_KEY='production-secret-key' ) sess.init_app(app) @app.route('/user/') def user_profile(user_id): session['last_viewed_user'] = user_id return f'Viewing user {user_id}' @app.route('/history') def view_history(): last_user = session.get('last_viewed_user', 'No history') return f'Last viewed user: {last_user}' return app app = create_app() if __name__ == '__main__': app.run() ``` -------------------------------- ### Direct Session Interface Initialization with Redis Source: https://github.com/pallets-eco/flask-session/blob/development/docs/usage.md Explains how to directly set the session interface for a Flask application to use a Redis backend. This method bypasses the `Session` class initialization and directly assigns a `RedisSessionInterface` instance. ```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) ``` -------------------------------- ### PostgreSQL Session Backend for Flask Source: https://context7.com/pallets-eco/flask-session/llms.txt Sets up Flask-Session to use PostgreSQL for storing session data. It relies on `psycopg2.pool` for connection pooling and requires a running PostgreSQL instance. This example tracks user visit counts. ```python from flask import Flask, session from flask_session import Session import psycopg2.pool app = Flask(__name__) # Create PostgreSQL connection pool pg_pool = psycopg2.pool.SimpleConnectionPool( 1, 20, host='localhost', database='myapp', user='postgres', password='password' ) app.config.update( SESSION_TYPE='postgresql', SESSION_POSTGRESQL=pg_pool, SESSION_POSTGRESQL_TABLE='flask_sessions', SESSION_POSTGRESQL_SCHEMA='public', SESSION_KEY_PREFIX='session:', SESSION_CLEANUP_N_REQUESTS=20 ) Session(app) @app.route('/visit') def track_visit(): visit_count = session.get('visit_count', 0) + 1 session['visit_count'] = visit_count return f'You have visited this page {visit_count} times' if __name__ == '__main__': app.run() ``` -------------------------------- ### Memcached Session Backend for Flask Source: https://context7.com/pallets-eco/flask-session/llms.txt Integrates Flask-Session with Memcached for session storage. It requires a running Memcached server and the `python-memcached` library. This example caches and retrieves data, demonstrating session persistence. ```python from flask import Flask, session from flask_session import Session import memcache app = Flask(__name__) # Create Memcached client mc_client = memcache.Client(['127.0.0.1:11211']) app.config.update( SESSION_TYPE='memcached', SESSION_MEMCACHED=mc_client, SESSION_KEY_PREFIX='session:', SESSION_PERMANENT=True, PERMANENT_SESSION_LIFETIME=1800 # 30 minutes ) Session(app) @app.route('/cache-data') def cache_data(): session['cached_result'] = 'expensive_computation_result' session['timestamp'] = '2025-12-11T12:00:00Z' return 'Data cached in session' @app.route('/retrieve-data') def retrieve_data(): result = session.get('cached_result', 'not cached') timestamp = session.get('timestamp', 'unknown') return {'result': result, 'timestamp': timestamp} if __name__ == '__main__': app.run() ``` -------------------------------- ### Configure Redis Session with Retries Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_guide.md Demonstrates how to configure a Redis client with custom retry logic for specific error types, including backoff strategy. This is relevant for SQL-based storage where retries are handled at the client level. ```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]) ``` -------------------------------- ### DynamoDB Session Backend for Flask Source: https://context7.com/pallets-eco/flask-session/llms.txt Configures Flask-Session to use AWS DynamoDB for session management. It requires the `boto3` library and AWS credentials. This example stores and retrieves user data and timestamps. ```python from flask import Flask, session from flask_session import Session import boto3 app = Flask(__name__) # Create DynamoDB client dynamodb_client = boto3.resource( 'dynamodb', region_name='us-east-1', aws_access_key_id='YOUR_ACCESS_KEY', aws_secret_access_key='YOUR_SECRET_KEY' ) app.config.update( SESSION_TYPE='dynamodb', SESSION_DYNAMODB=dynamodb_client, SESSION_DYNAMODB_TABLE='SessionData', SESSION_DYNAMODB_TABLE_EXISTS=True, # Set False to auto-create table SESSION_KEY_PREFIX='app_session:', SESSION_PERMANENT=True ) Session(app) @app.route('/store') def store_in_dynamodb(): session['user_data'] = {'name': 'Alice', 'role': 'admin'} session['timestamp'] = 1702294800 return 'Data stored in DynamoDB' @app.route('/retrieve') def retrieve_from_dynamodb(): user_data = session.get('user_data', {}) return {'user_data': user_data} if __name__ == '__main__': app.run() ``` -------------------------------- ### Configure CacheLib Session Backend with Flask Source: https://context7.com/pallets-eco/flask-session/llms.txt This snippet shows how to configure Flask-Session to use a CacheLib backend, specifically Redis, for session management. It sets up connection parameters, session types, and serialization formats. The example includes routes for storing and retrieving data using the configured session. ```python from flask import Flask, session from flask_session import Session from cachelib import RedisCache cache = RedisCache(host='localhost', port=6379, default_timeout=3600) app = Flask(__name__) app.config.update( SESSION_TYPE='cachelib', SESSION_CACHELIB=cache, SESSION_KEY_PREFIX='cachelib_session:', SESSION_PERMANENT=True, SESSION_SERIALIZATION_FORMAT='json' ) Session(app) @app.route('/cachelib-store') def cachelib_store(): session['data'] = 'stored via cachelib' return 'Data stored' @app.route('/cachelib-retrieve') def cachelib_retrieve(): return {'data': session.get('data', 'not found')} if __name__ == '__main__': app.run() ``` -------------------------------- ### Implement Secure Session Regeneration in Flask Source: https://context7.com/pallets-eco/flask-session/llms.txt This example demonstrates how to enhance session security by regenerating the session ID upon user login. This mitigates session fixation attacks. It configures Flask-Session with a Redis backend and includes routes for login, logout, and accessing protected resources, checking for authentication status. ```python from flask import Flask, session from flask_session import Session app = Flask(__name__) app.config.update( SESSION_TYPE='redis', SECRET_KEY='secure-secret-key' ) Session(app) @app.route('/login', methods=['POST']) def login(): # Regenerate session ID to prevent session fixation attacks app.session_interface.regenerate(session) # Set authenticated user data session['authenticated'] = True session['user_id'] = 42 session['username'] = 'secure_user' return {'status': 'logged in', 'new_session_id': session.sid} @app.route('/logout') def logout(): # Clear all session data session.clear() return {'status': 'logged out'} @app.route('/protected') def protected_route(): if not session.get('authenticated'): return {'error': 'Unauthorized'}, 401 return {'message': 'Access granted', 'user': session.get('username')} if __name__ == '__main__': app.run() ``` -------------------------------- ### SQLAlchemy Session Backend for Flask Source: https://context7.com/pallets-eco/flask-session/llms.txt Configures Flask-Session to use SQLAlchemy as the session backend. It requires SQLAlchemy to be installed and configured, and it stores session data in a specified database table. Session data includes theme, language, and notification preferences. ```python from flask import Flask, session from flask_session import Session from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # Configure SQLAlchemy app.config.update( SQLALCHEMY_DATABASE_URI='sqlite:///sessions.db', SESSION_TYPE='sqlalchemy', SESSION_SQLALCHEMY_TABLE='user_sessions', SESSION_KEY_PREFIX='app:', SESSION_PERMANENT=True, SESSION_CLEANUP_N_REQUESTS=10, # Cleanup expired sessions every 10 requests SECRET_KEY='dev-secret-key' ) # Initialize SQLAlchemy db = SQLAlchemy(app) app.config['SESSION_SQLALCHEMY'] = db # Initialize session Session(app) @app.route('/preferences/set') def set_preferences(): session['theme'] = 'dark' session['language'] = 'en' session['notifications'] = True return 'Preferences saved' @app.route('/preferences/get') def get_preferences(): return { 'theme': session.get('theme', 'light'), 'language': session.get('language', 'en'), 'notifications': session.get('notifications', False) } if __name__ == '__main__': app.run() ``` -------------------------------- ### Configure Redis Session Backend Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_guide.md Sets the session type to Redis and configures the Redis connection instance. It's recommended to provide your own redis.Redis() instance for flexibility, especially in production. If not provided, Flask-Session creates a default instance for local development. ```python app.config['SESSION_TYPE'] = 'redis' app.config['SESSION_REDIS'] = Redis.from_url('redis://127.0.0.1:6379') ``` -------------------------------- ### Scheduled Session Cleanup Command Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_guide.md Provides the command to manually trigger session cleanup for storage engines like SQLAlchemy that do not support time-to-live. This command should be run regularly using a scheduler like cron or Heroku Scheduler. ```bash flask session_cleanup ``` -------------------------------- ### Handle Redis Errors with Flask Error Handling Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_exceptions.md Provides an example of implementing a custom error handler in Flask to manage Redis-specific errors. This handler logs the error for debugging purposes and returns a user-friendly message with a 500 status code, improving the end-user experience during service disruptions. ```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 ``` -------------------------------- ### Memcached Session Interface Configuration for Flask-Session Source: https://github.com/pallets-eco/flask-session/blob/development/docs/api.md Provides an example of how to configure the MemcachedSessionInterface for Flask-Session. This interface uses Memcached for storing session data and requires appropriate client libraries. Configuration options include client instance, key prefix, signer usage, session permanence, ID length, and serialization format. ```python from flask import Flask from flask_session.memcached import MemcachedSessionInterface import memcache # Assuming pylibmc, python-memcached, or similar is installed app = Flask(__name__) # Example Memcache client setup (replace with your actual client configuration) client = memcache.Client(['127.0.0.1:11211'], debug=0) app.session_interface = MemcachedSessionInterface( app, client=client, key_prefix='my_app_session:', use_signer=True, permanent=True, sid_length=32, serialization_format='msgpack' ) ``` -------------------------------- ### Handle Redis Errors Gracefully in Flask Sessions Source: https://context7.com/pallets-eco/flask-session/llms.txt This code illustrates how to implement error handling for session backend operations, specifically targeting Redis errors. It configures a Flask application with a Redis session backend and defines an error handler for `redis.exceptions.RedisError`. The example includes routes for safe session writes and reads, demonstrating try-except blocks to catch potential `RedisError` exceptions. ```python from flask import Flask, session from flask_session import Session from redis.exceptions import RedisError import logging app = Flask(__name__) app.config.update( SESSION_TYPE='redis', SECRET_KEY='error-handling-key' ) Session(app) # Configure logging logging.basicConfig(level=logging.ERROR) @app.errorhandler(RedisError) def handle_redis_error(error): app.logger.error(f'Redis session error: {error}') return { 'error': 'Session service temporarily unavailable', 'message': 'Please try again later' }, 503 @app.route('/safe-session-write') def safe_session_write(): try: session['data'] = 'important_value' session['timestamp'] = '2025-12-11' return {'status': 'success'} except RedisError as e: app.logger.error(f'Failed to write session: {e}') return {'status': 'error', 'message': 'Session write failed'}, 500 @app.route('/safe-session-read') def safe_session_read(): try: data = session.get('data', 'default_value') return {'data': data} except RedisError as e: app.logger.error(f'Failed to read session: {e}') return {'status': 'error', 'message': 'Session read failed'}, 500 if __name__ == '__main__': app.run() ``` -------------------------------- ### Configure Flask-Session Lifetime and Security (Python) Source: https://context7.com/pallets-eco/flask-session/llms.txt This snippet shows how to configure Flask-Session for custom session lifetimes and security. It sets the session type to Redis, makes sessions permanent with a 2-hour expiration, refreshes the session on each request, and configures secure, HttpOnly, and SameSite cookie attributes. It also includes example routes for managing long and short-lived sessions. ```python from flask import Flask, session from flask_session import Session from datetime import timedelta app = Flask(__name__) app.config.update( SESSION_TYPE='redis', SESSION_PERMANENT=True, PERMANENT_SESSION_LIFETIME=timedelta(hours=2), # 2 hour expiration SESSION_REFRESH_EACH_REQUEST=True, # Refresh session on each request SESSION_COOKIE_SECURE=True, # Only send cookie over HTTPS SESSION_COOKIE_HTTPONLY=True, # Prevent JavaScript access SESSION_COOKIE_SAMESITE='Lax', # CSRF protection SECRET_KEY='lifetime-config-key' ) Session(app) @app.route('/long-session') def long_session(): session.permanent = True # Explicitly mark as permanent session['data'] = 'long-lived data' return 'Session will last 2 hours' @app.route('/short-session') def short_session(): session.permanent = False # Non-permanent (browser session) session['temp_data'] = 'browser session only' return 'Session lasts until browser closes' @app.route('/check-lifetime') def check_lifetime(): return { 'is_permanent': session.permanent, 'session_id': session.sid } if __name__ == '__main__': app.run() ``` -------------------------------- ### Store and Modify Nested Data Structures in Flask Session Source: https://context7.com/pallets-eco/flask-session/llms.txt This example demonstrates how to store complex, nested data structures within the Flask session using a Redis backend and MessagePack serialization. It includes routes to store a detailed user profile, modify nested preferences, and retrieve the complex session data. The use of `session.modified = True` is highlighted for ensuring nested changes are persisted. ```python from flask import Flask, session from flask_session import Session app = Flask(__name__) app.config.update( SESSION_TYPE='redis', SESSION_SERIALIZATION_FORMAT='msgpack' ) Session(app) @app.route('/complex-data') def store_complex_data(): # Store complex nested structures session['user_profile'] = { 'id': 123, 'name': 'Jane Doe', 'preferences': { 'theme': 'dark', 'language': 'en', 'notifications': ['email', 'push'] }, 'history': [ {'page': '/home', 'timestamp': 1702294800}, {'page': '/profile', 'timestamp': 1702294900} ] } session.modified = True # Important for nested modifications return 'Complex data stored' @app.route('/modify-nested') def modify_nested(): profile = session.get('user_profile', {}) if 'preferences' in profile: profile['preferences']['theme'] = 'light' session['user_profile'] = profile session.modified = True # Mark as modified return 'Nested data updated' @app.route('/get-complex') def get_complex_data(): return session.get('user_profile', {}) if __name__ == '__main__': app.run() ``` -------------------------------- ### Build documentation with Make Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Builds the project documentation locally using Make, which orchestrates the Sphinx build process. This is useful for previewing changes to the documentation. ```bash cd docs make html ``` -------------------------------- ### Build documentation with Sphinx Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Builds the project documentation locally using Sphinx directly. This command specifies the builder ('html') and the source and output directories. ```bash sphinx-build -b html docs docs/_build ``` -------------------------------- ### Basic Flask Application with Server-Side Sessions Source: https://github.com/pallets-eco/flask-session/blob/development/README.md Demonstrates a minimal Flask application configured to use server-side sessions with Flask-Session. It initializes the Flask app, configures the session type to 'redis', and sets up routes to store and retrieve session data. Requires a running Redis instance. ```python from flask import Flask, session from flask_session import Session app = Flask(__name__) # Check Configuration section for more details SESSION_TYPE = 'redis' 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') ``` -------------------------------- ### Flask App with Custom Redis Client Configuration Source: https://context7.com/pallets-eco/flask-session/llms.txt Shows how to configure Flask-Session to use a custom-initialized Redis client. This allows for more granular control over the Redis connection, such as specifying passwords, databases, and decoding responses. It also demonstrates setting various session configurations like key prefix, permanence, and serialization format. ```python from flask import Flask, session from flask_session import Session import redis app = Flask(__name__) # Create custom Redis client redis_client = redis.Redis( host='localhost', port=6379, db=0, password='your-redis-password', decode_responses=False ) app.config.update( SESSION_TYPE='redis', SESSION_REDIS=redis_client, SESSION_KEY_PREFIX='app_session:', SESSION_PERMANENT=True, PERMANENT_SESSION_LIFETIME=3600, # 1 hour SESSION_ID_LENGTH=32, SESSION_SERIALIZATION_FORMAT='msgpack' ) Session(app) @app.route('/login', methods=['POST']) def login(): # Assuming authentication is successful session['authenticated'] = True session['user_email'] = 'user@example.com' session['permissions'] = ['read', 'write'] return {'status': 'logged in', 'session_id': session.sid} @app.route('/check-auth') def check_auth(): if session.get('authenticated'): return { 'authenticated': True, 'email': session.get('user_email'), 'permissions': session.get('permissions') } return {'authenticated': False}, 401 if __name__ == '__main__': app.run() ``` -------------------------------- ### Initialize Flask-Session with Flask App Source: https://github.com/pallets-eco/flask-session/blob/development/docs/api.md Demonstrates the typical initialization of Flask-Session by directly passing a Flask application instance to the Session class. This is a straightforward way to enable server-side sessions for a Flask application. ```python from flask import Flask from flask_session import Session app = Flask(__name__) Session(app) ``` -------------------------------- ### FileSystemSessionInterface Initialization in Python Source: https://github.com/pallets-eco/flask-session/blob/development/docs/api.md Initializes the FileSystemSessionInterface for Flask applications. This class allows for file-based session storage using cachelib's FileSystemCache. Key parameters include session ID length, serialization format, and the directory for storing session files. The use_signer, permanent, and key_prefix parameters control security and session behavior. ```python from flask_session.filesystem import FileSystemSessionInterface # Example initialization with custom parameters app.session_interface = FileSystemSessionInterface( app=app, key_prefix='my_session:', use_signer=True, permanent=False, sid_length=64, serialization_format='json', cache_dir='/path/to/session/files', threshold=1000, mode=0o666 ) ``` -------------------------------- ### CacheLib Session Backend for Flask (Redis) Source: https://context7.com/pallets-eco/flask-session/llms.txt Demonstrates using CacheLib with Redis as a session backend for Flask. This configuration requires a running Redis instance and the `cachelib` library. It allows for efficient session management with Redis. ```python from flask import Flask, session from flask_session import Session from cachelib import RedisCache app = Flask(__name__) # Note: CacheLib configuration for Flask-Session typically involves setting # SESSION_TYPE to 'redis' and providing a RedisCache instance or connection details. # The CacheLib library itself is used to create the cache instance. # Example using RedisCache directly (assuming Redis is running on default port): # If using CacheLib's RedisCache, you'd typically pass its configuration # or the instance itself to Flask-Session depending on how CacheLib is integrated. # For Flask-Session, you often pass connection details directly or a client object. # A common way to integrate CacheLib with Flask-Session when using Redis: # app.config.update( # SESSION_TYPE='redis', # SESSION_REDIS_HOST='localhost', # SESSION_REDIS_PORT=6379, # SESSION_REDIS_DB=0, # SESSION_KEY_PREFIX='session:', # SESSION_PERMANENT=True, # PERMANENT_SESSION_LIFETIME=3600 # 1 hour # ) # If CacheLib is used to manage the Redis client that Flask-Session connects to: # redis_cache = RedisCache(host='localhost', port=6379, db=0) # app.config['SESSION_REDIS'] = redis_cache.client # This part depends on Flask-Session's specific integration. # For direct use with Flask-Session and Redis, the configuration might look like: app.config.update( SESSION_TYPE='redis', SESSION_REDIS_HOST='localhost', SESSION_REDIS_PORT=6379, SESSION_REDIS_DB=0, SESSION_KEY_PREFIX='cachelib_session:', SESSION_PERMANENT=True ) # Note: The exact integration might vary based on the Flask-Session version and # how CacheLib is intended to be used with it. The following is a placeholder # assuming a standard Redis configuration for Flask-Session. Session(app) @app.route('/cachelib-data') def cachelib_data(): session['cachelib_key'] = 'cachelib_value' return 'Data stored using CacheLib via Redis backend' @app.route('/get-cachelib-data') def get_cachelib_data(): return {'value': session.get('cachelib_key', 'not found')} if __name__ == '__main__': app.run() ``` -------------------------------- ### Configure Flask-Session CacheLib Backend Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_reference.md Demonstrates how to configure the CacheLib backend for Flask-Session. This involves initializing a CacheLib backend instance, such as FileSystemCache, and assigning it to the SESSION_CACHELIB configuration key. The configuration should be done before passing the app to Flask-Session. Note that default_timeout in CacheLib backends is overridden by PERMANENT_SESSION_LIFETIME. ```python from flask_session.sessions import FileSystemCache app.config['SESSION_CACHELIB'] = FileSystemCache(cache_dir='flask_session', threshold=500) ``` -------------------------------- ### CacheLibSessionInterface Initialization in Python Source: https://github.com/pallets-eco/flask-session/blob/development/docs/api.md Initializes the CacheLibSessionInterface for Flask applications, enabling session storage with any cachelib backend. This interface supports common session configurations like key prefix, signer usage, session permanence, session ID length, and serialization format. It can be initialized with an existing cachelib client instance. ```python from flask_session.cachelib import CacheLibSessionInterface from cachelib import FileSystemCache # Example initialization with a FileSystemCache client cache_client = FileSystemCache(cache_dir='/path/to/cache') app.session_interface = CacheLibSessionInterface( app=app, client=cache_client, key_prefix='app_session:', use_signer=False, permanent=True, sid_length=32, serialization_format='msgpack' ) ``` -------------------------------- ### Deprecated Configuration Options Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_reference.md Configuration options that have been deprecated. ```APIDOC ## Deprecated Configuration Options **Deprecated since version 0.7.0:** `SESSION_FILE_DIR`, `SESSION_FILE_THRESHOLD`, `SESSION_FILE_MODE`. Use `SESSION_CACHELIB` instead. ``` -------------------------------- ### Run tests with Pytest Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Executes the project's test suite using Pytest. This command can run all tests or specific test files to verify the functionality of Flask-Session. ```bash pytest tests pytest tests/test_basic.py ``` -------------------------------- ### SQLAlchemy Session Configuration Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_reference.md Configuration options for using SQLAlchemy as a session backend. ```APIDOC ## SQLAlchemy Session Configuration ### SESSION_SQLALCHEMY **Description:** A `flask_sqlalchemy.SQLAlchemy` instance whose database connection URI is configured using the `SQLALCHEMY_DATABASE_URI` parameter. Must be set in flask_sqlalchemy version 3.0 or higher. ### SESSION_SQLALCHEMY_TABLE **Description:** The name of the SQL table you want to use for storing sessions. **Default:** `'sessions'` ### SESSION_SQLALCHEMY_SEQUENCE **Description:** The name of the sequence you want to use for the primary key in the SQLAlchemy table. **Default:** `None` **Version Added:** 0.6.0 ### SESSION_SQLALCHEMY_SCHEMA **Description:** The name of the schema you want to use for the SQLAlchemy table. **Default:** `None` **Version Added:** 0.6.0 ### SESSION_SQLALCHEMY_BIND_KEY **Description:** The name of the bind key you want to use for the SQLAlchemy connection. **Default:** `None` **Version Added:** 0.6.0 ``` -------------------------------- ### MongoDB Session Configuration Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_reference.md Configuration options for using MongoDB as a session backend. ```APIDOC ## MongoDB Session Configuration ### SESSION_MONGODB_COLLECT **Description:** The MongoDB collection you want to use for storing sessions. **Default:** `'sessions'` ``` -------------------------------- ### Lint code with Ruff Source: https://github.com/pallets-eco/flask-session/blob/development/docs/contributing.md Runs the Ruff linter to check for code style violations and automatically fixes them. This ensures code quality and consistency across the project. ```bash ruff check --fix ``` -------------------------------- ### DynamoDB Session Configuration Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_reference.md Configuration options for using DynamoDB as a session backend. ```APIDOC ## DynamoDB Session Configuration ### SESSION_DYNAMODB **Description:** A `boto3.resource` instance for interacting with DynamoDB. **Default:** Instance connected to `'localhost:8000'` ### SESSION_DYNAMODB_TABLE_NAME **Description:** The name of the DynamoDB table you want to use for storing sessions. **Default:** `'Sessions'` ### SESSION_DYNAMODB_TABLE_EXISTS **Description:** By default, Flask-Session creates a new DynamoDB table with TTL settings activated. If set to `True`, it assumes the table already exists. **Default:** `False` ``` -------------------------------- ### Session Cleanup Configuration Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_reference.md Configuration option for session cleanup. ```APIDOC ## Session Cleanup Configuration ### SESSION_CLEANUP_N_REQUESTS **Description:** Only applicable to non-TTL backends. Specifies the average number of requests after which Flask-Session will perform a session cleanup. This involves removing all session data older than `PERMANENT_SESSION_LIFETIME`. Using the app command `flask session_cleanup` is preferable. **Default:** `None` **Version Added:** 0.7.0 ``` -------------------------------- ### Casting Unsupported Types to Supported Types in Python Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_serialization.md Demonstrates how to cast an object of an unsupported type (LazyString) to a supported string type for session serialization. This is useful when encountering TypeErrors due to unsupported object types. ```python session["status"] = str(LazyString('done')) ``` -------------------------------- ### Configure Redis Retries with Backoff in Flask-Session Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_exceptions.md Demonstrates how to configure retry logic for Redis client connections in Flask-Session. It utilizes exponential backoff for up to 3 retries on specific Redis errors like BusyLoadingError, ConnectionError, and TimeoutError. This ensures resilience against transient network or server 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]) ``` -------------------------------- ### Overriding Flask-Session Serializer with orjson in Python Source: https://github.com/pallets-eco/flask-session/blob/development/docs/config_serialization.md Shows how to replace the default Flask-Session serializer with a custom one, specifically using the 'orjson' library. This is achieved by assigning an object with 'dumps' and 'loads' methods to 'app.session_interface.serializer'. ```python from flask_session import Session import orjson app = Flask(__name__) Session(app) # Override the serializer app.session_interface.serializer = orjson ``` -------------------------------- ### Regenerate Session ID on Login in Flask Source: https://github.com/pallets-eco/flask-session/blob/development/docs/security.md Demonstrates how to regenerate the session identifier upon user login to mitigate session fixation attacks. This is achieved by calling the `regenerate()` method on the session interface. Ensure your session interface supports this method, as defined in `flask_session.base.ServerSideSession`. ```python from flask import Flask, session app = Flask(__name__) # Assume session is properly configured and initialized @app.route('/login') def login(): # your login logic ... # Regenerate session ID to prevent session fixation app.session_interface.regenerate(session) # your response ... return "Logged in and session regenerated." ``` -------------------------------- ### Regenerate Session ID in Flask-Session Source: https://github.com/pallets-eco/flask-session/blob/development/docs/api.md Shows how to regenerate the session ID for a given session object. This is achieved by calling the `regenerate` method, typically accessed through the session interface. This is a security measure to prevent session fixation. ```python from flask import session as flask_session from flask_session.base import ServerSideSession # Assuming 'flask_session' is an instance of ServerSideSession # This is a conceptual example as direct access to session_interface.regenerate is usually done implicitly # by Flask. def regenerate_session(session: ServerSideSession): # In a real Flask app, this would be accessed via flask.session_interface.regenerate(flask_session) # For demonstration, we'll assume a direct call if available or through the interface. # Example: flask.session_interface.regenerate(flask_session) pass # Placeholder for actual regeneration logic ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.