{"id":1243,"library":"flask-session","title":"Flask-Session","description":"Flask-Session is an official extension for Flask that provides support for server-side session management. Instead of storing session data directly in client-side cookies (which can be size-limited and less secure), it stores it on the server using various backends like Redis, Memcached, FileSystem, MongoDB, SQLAlchemy, or DynamoDB. The current version is 0.8.0, and it is actively maintained by the Pallets organization, ensuring regular updates and compatibility with Flask. [1, 5, 15, 16]","status":"active","version":"0.8.0","language":"python","source_language":"en","source_url":"https://github.com/pallets-eco/flask-session","tags":["Flask","session","server-side session","web","extension","Redis","MongoDB","SQLAlchemy"],"install":[{"cmd":"pip install flask-session","lang":"bash","label":"Basic installation"},{"cmd":"pip install 'flask-session[redis]' # For Redis backend\npip install 'flask-session[cachelib]' # For CacheLib backend (replaces FileSystem)\npip install 'flask-session[mongodb]' # For MongoDB backend\npip install 'flask-session[sqlalchemy]' # For SQLAlchemy backend\npip install 'flask-session[dynamodb]' # For DynamoDB backend","lang":"bash","label":"With specific backend dependencies"}],"dependencies":[{"reason":"Core web framework dependency for the extension.","package":"Flask","optional":false},{"reason":"Required for RedisSessionInterface.","package":"redis","optional":true},{"reason":"Required for CacheLibSessionInterface, which replaced FileSystemSessionInterface.","package":"cachelib","optional":true},{"reason":"Required for MongoDBSessionInterface.","package":"pymongo","optional":true},{"reason":"Required for SqlAlchemySessionInterface.","package":"SQLAlchemy","optional":true},{"reason":"Required for DynamoDBSessionInterface (added in v0.8.0).","package":"boto3","optional":true}],"imports":[{"symbol":"Session","correct":"from flask_session import Session"},{"note":"The 'Session' class from 'flask_session' is for initializing the extension; the 'session' proxy object for accessing/modifying session data comes from 'flask' itself, just like Flask's built-in session. [3, 4]","wrong":"from flask_session import session","symbol":"session","correct":"from flask import session"}],"quickstart":{"code":"import os\nfrom flask import Flask, session, redirect, url_for\nfrom flask_session import Session\nfrom redis import Redis\n\napp = Flask(__name__)\n\n# Configuration for server-side sessions\napp.config[\"SECRET_KEY\"] = os.environ.get(\"FLASK_SECRET_KEY\", \"super-secret-key-that-should-be-random-and-long\")\napp.config[\"SESSION_TYPE\"] = \"redis\"\napp.config[\"SESSION_PERMANENT\"] = False # Set to True for permanent sessions\n\n# Configure Redis client (replace with your Redis connection details)\n# For production, consider using environment variables for host/port/password\napp.config[\"SESSION_REDIS\"] = Redis(host=os.environ.get(\"REDIS_HOST\", \"localhost\"), port=6379, db=0)\n\n# Initialize Flask-Session\nSession(app)\n\n@app.route('/')\ndef index():\n    if 'username' in session:\n        return f'Hello, {session[\"username\"]}! <a href=\"/logout\">Logout</a>'\n    return 'You are not logged in. <a href=\"/login\">Login</a>'\n\n@app.route('/login')\ndef login():\n    # Simulate a login, in a real app this would involve forms and authentication\n    session['username'] = 'testuser'\n    return redirect(url_for('index'))\n\n@app.route('/logout')\ndef logout():\n    session.pop('username', None)\n    return redirect(url_for('index'))\n\nif __name__ == '__main__':\n    app.run(debug=True)","lang":"python","description":"This quickstart demonstrates how to set up Flask-Session with a Redis backend. It configures the Flask application with a secret key (essential for session security) and specifies Redis as the session storage type. The example includes simple routes to set, get, and clear session data, showcasing how `flask.session` is used once `flask_session.Session` is initialized. Remember to install `redis` (`pip install 'flask-session[redis]'`) for this example to work. [3, 8]"},"warnings":[{"fix":"Upgrade to 0.7.0+ and ensure all active sessions are accessed/modified to trigger migration to `msgspec` before upgrading to 1.0.0. Configure `SESSION_SERIALIZATION_FORMAT = 'json'` if you need a human-readable format or have specific compatibility needs, though `msgpack` (default) is more efficient. [10]","message":"The default session serialization format changed from `pickle` to `msgspec` in version 0.7.0. While 0.7.0 attempts to convert existing `pickle` sessions upon read/write, `pickle` support will be entirely removed in version 1.0.0. Any un-migrated `pickle` sessions will be cleared upon access in 1.0.0. [5, 7, 10]","severity":"breaking","affected_versions":"0.7.0+"},{"fix":"Remove `SESSION_USE_SIGNER` from your configuration as `sid_length` now provides the relevant entropy. Migrate from `SESSION_TYPE = 'filesystem'` to `SESSION_TYPE = 'cachelib'` and ensure `cachelib` is installed. [7, 10]","message":"The `SESSION_USE_SIGNER` configuration option and `FileSystemSessionInterface` were deprecated in version 0.7.0. `FileSystemSessionInterface` is replaced by `CacheLibSessionInterface` which uses `cachelib` under the hood. [7, 10]","severity":"deprecated","affected_versions":"0.7.0+"},{"fix":"Always configure a strong, random `SECRET_KEY` in your Flask application. For production, load this from environment variables or a secure configuration system. `app.config[\"SECRET_KEY\"] = os.environ.get(\"FLASK_SECRET_KEY\")`","message":"It is crucial to set `app.config[\"SECRET_KEY\"]` when using Flask-Session, even though sessions are server-side. This secret key is used to cryptographically sign the session ID cookie that is sent to the client, preventing tampering and ensuring session integrity. [8, 12]","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always use `from flask import session` and then interact with `session['key']` or `session.get('key')` within your application code after initializing Flask-Session with `Session(app)`. [3]","message":"Flask-Session's `Session` class is for initializing the extension with your Flask application. To access or modify the current session data within your routes, you must import and use `flask.session`, which is Flask's built-in session proxy. Attempting to use the `Session` instance directly for data access will not work as expected. [3, 4]","severity":"gotcha","affected_versions":"All versions"},{"fix":"Be mindful of `PERMANENT_SESSION_LIFETIME`'s impact on your server-side session data lifespan. For non-permanent sessions that expire with the browser, ensure `SESSION_PERMANENT = False` and understand its limitations regarding server-side cleanup. [10]","message":"The `PERMANENT_SESSION_LIFETIME` configured in Flask's app config (e.g., `app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=30)`) is used by Flask-Session to set the expiration time for the *server-side session data*, not just the client-side cookie. This applies regardless of whether `SESSION_PERMANENT` is set to `True` or `False`. [2, 10]","severity":"gotcha","affected_versions":"All versions"},{"fix":"Avoid requesting `flask-session[dynamodb]` as an extra. Consult the official Flask-Session documentation for supported backends and installation extras. If DynamoDB integration is required, explore third-party extensions or implement a custom session interface using `boto3`.","message":"Flask-Session does not provide a native `dynamodb` session interface or a `[dynamodb]` installation extra. Requesting `flask-session[dynamodb]` will result in a pip warning that the extra is not provided. If you need DynamoDB support, you may need to use a separate extension or implement a custom session interface.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'0.8.0':63 '1':80 '15':82 '16':83 '5':81 'activ':67 'backend':50 'client':30 'client-sid':29 'compat':77 'cooki':32 'current':60 'data':26 'direct':27 'dynamodb':58 'ensur':73 'extens':10,91 'filesystem':54 'flask':2,5,12,79,84 'flask-sess':1,4 'instead':22 'less':40 'like':51 'limit':38 'maintain':68 'manag':21 'memcach':53 'mongodb':55,93 'offici':9 'organ':72 'pallet':71 'provid':14 'redi':52,92 'regular':74 'secur':41 'server':18,47,87 'server-sid':17,86 'session':3,6,20,25,85,89 'side':19,31,88 'size':37 'size-limit':36 'sqlalchemi':56,94 'store':24,43 'support':15 'updat':75 'use':48 'various':49 'version':61 'web':90","created_at":"2026-04-06T16:56:10.344652+00:00","updated_at":"2026-04-16T15:08:04.279216+00:00","problems":[{"fix":"Set a strong, unique, and secret key in your Flask application configuration. It's best practice to load this from an environment variable for production.\n```python\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your_super_secret_key_here' # In production, load from env var\n# Or, for Flask 0.10 and later:\n# app.secret_key = 'your_super_secret_key_here'\n```","cause":"Flask's session mechanism, which Flask-Session relies on, requires a secret key for cryptographic signing of session cookies to ensure their integrity and authenticity. This error occurs when `app.secret_key` is not set or not configured correctly before the session is accessed.","error":"RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret."},{"fix":"Configure the `SESSION_TYPE` in your Flask application to one of the supported backends (e.g., 'filesystem', 'redis', 'memcached', 'mongodb', 'sqlalchemy', 'cachelib').\n```python\nfrom flask import Flask\nfrom flask_session import Session\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your_secret_key'\napp.config['SESSION_TYPE'] = 'filesystem' # Or 'redis', 'memcached', etc.\nsess = Session()\nsess.init_app(app)\n```","cause":"When using `flask-session`, the default session interface (`NullSessionInterface`) is used if `SESSION_TYPE` is not explicitly configured, which is designed to raise an error when session operations are attempted to indicate that a proper server-side session backend hasn't been chosen.","error":"RuntimeError: The session is unavailable because no SESSION_TYPE is configured."},{"fix":"Ensure the Redis server is running and accessible from your Flask application. Verify the `SESSION_REDIS` configuration points to the correct Redis instance.\n```python\nfrom flask import Flask\nfrom flask_session import Session\nfrom redis import Redis\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your_secret_key'\napp.config['SESSION_TYPE'] = 'redis'\napp.config['SESSION_REDIS'] = Redis(host='localhost', port=6379, db=0)\nsess = Session()\nsess.init_app(app)\n```\nAlso, check your Redis server status (e.g., `redis-cli ping` or `sudo systemctl status redis`) and firewall rules.","cause":"This error occurs when `flask-session` is configured to use Redis as its session backend, but the application cannot establish a connection with the Redis server. This usually means the Redis server is not running, is running on a different host/port, or a firewall is blocking the connection.","error":"redis.exceptions.ConnectionError: Error 10061 connecting to 127.0.0.1:6379. No connection could be made because the target machine actively refused it."},{"fix":"Install `flask-session` using pip in your active Python environment. If using a virtual environment, ensure it's activated.\n```bash\npip install Flask-Session\n# If using Python 3 and have multiple Python versions:\npip3 install Flask-Session\n```","cause":"This error indicates that the `flask-session` library has not been installed in the Python environment where your Flask application is being run, or it was installed for a different Python version/environment.","error":"ModuleNotFoundError: No module named 'flask_session'"},{"fix":"Ensure `SECRET_KEY` is set and loaded correctly (especially outside `if __name__ == '__main__':` blocks for production). Confirm `SESSION_TYPE` is properly configured for a persistent backend (e.g., 'filesystem', 'redis'). If deploying with a proxy or HTTPS, set `SESSION_COOKIE_SECURE=True` and `SESSION_COOKIE_SAMESITE='Lax'` or `'None'` (if cross-site) along with a `SECRET_KEY`.\n```python\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your_strong_secret_key'\napp.config['SESSION_TYPE'] = 'filesystem'\napp.config['SESSION_PERMANENT'] = False # If you want non-permanent sessions\napp.config['SESSION_COOKIE_SECURE'] = True # Use True in production with HTTPS\napp.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # Or 'None' with SECURE=True for cross-site\nsess = Session()\nsess.init_app(app)\n```","cause":"While not a specific error message, this common problem happens when Flask-Session is not configured correctly, leading to session data not being retained between HTTP requests. Common causes include missing `SECRET_KEY`, incorrect `SESSION_TYPE` setup, issues with how the application is run (e.g., not loading config in WSGI), or cookie-related problems like `SESSION_COOKIE_SAMESITE` not being correctly configured for cross-site requests.","error":"Flask sessions don't persist data / Session data disappears across requests"}],"ecosystem":"pypi","meta_description":null,"install_score":80,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.8.0","cli_name":"","cli_version":null,"type":"library","homepage":"https://flask-session.palletsprojects.com","github":"https://github.com/pallets-eco/flask-session","docs":"https://flask-session.readthedocs.io","changelog":"https://flask-session.readthedocs.io/changes.html","pypi":"https://pypi.org/project/flask-session/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["web-framework","database"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":"verified"}}