The Flask session object lets you save small pieces of information about a user while they browse your website. It helps keep track of things like login status or preferences without needing a database.
Flask session object
from flask import session # Set a value session['key'] = 'value' # Get a value value = session.get('key') # Remove a value session.pop('key', None)
The session object works like a dictionary to store key-value pairs.
Flask signs the session data to keep it secure but stores it on the client side by default.
session['username'] = 'alice'
user = session.get('username')session.pop('username', None)
This simple Flask app uses the session object to remember if a user is logged in. When the user posts their username to /login, it saves it in the session. The index page shows if the user is logged in or not. The /logout route clears the session.
from flask import Flask, session, redirect, url_for, request app = Flask(__name__) app.secret_key = 'supersecretkey' @app.route('/') def index(): if 'username' in session: return f"Logged in as {session['username']}" return 'You are not logged in' @app.route('/login', methods=['POST']) def login(): username = request.form['username'] session['username'] = username return redirect(url_for('index')) @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('index'))
Always set app.secret_key to keep session data secure.
Session data is stored client-side in cookies, so keep it small and avoid sensitive info.
Use session.get() to avoid errors if a key is missing.
The Flask session object stores user data temporarily during their visit.
It works like a dictionary and keeps data between requests.
Remember to set a secret key to protect session data.