Flask-Session

0.8.0 · active · verified Mon Apr 06

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]

Warnings

Install

Imports

Quickstart

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]

import os
from flask import Flask, session, redirect, url_for
from flask_session import Session
from redis import Redis

app = Flask(__name__)

# Configuration for server-side sessions
app.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET_KEY", "super-secret-key-that-should-be-random-and-long")
app.config["SESSION_TYPE"] = "redis"
app.config["SESSION_PERMANENT"] = False # Set to True for permanent sessions

# Configure Redis client (replace with your Redis connection details)
# For production, consider using environment variables for host/port/password
app.config["SESSION_REDIS"] = Redis(host=os.environ.get("REDIS_HOST", "localhost"), port=6379, db=0)

# Initialize Flask-Session
Session(app)

@app.route('/')
def index():
    if 'username' in session:
        return f'Hello, {session["username"]}! <a href="/logout">Logout</a>'
    return 'You are not logged in. <a href="/login">Login</a>'

@app.route('/login')
def login():
    # Simulate a login, in a real app this would involve forms and authentication
    session['username'] = 'testuser'
    return redirect(url_for('index'))

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)

view raw JSON →