Flask by Example: Session Data Storage
Sessions allow you to store information specific to a user from one request to the next. Unlike plain cookies, Flask sessions are cryptographically signed, meaning users can see the data but cannot modify it unless they know the secret key.
Code
from flask import Flask, session, redirect, url_for, request
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@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=['GET', 'POST'])
def login():
if request.method == 'POST':
# Store data in the session dict
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# Remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))Explanation
The session object allows you to persist data across requests for a specific user. Unlike plain cookies, Flask sessions are cryptographically signed using app.secret_key, which prevents the client from tampering with the data.
Sessions are the standard way to implement stateful features like user logins. The data is stored on the client side in a cookie, but because of the signature, the server can trust that it hasn't been modified.
It is important to note that while the data is tamper-proof, it is not encrypted. The user can still see the contents of the session (it is base64 encoded), so you should not store sensitive secrets directly in the session.
Code Breakdown
app.secret_key is required to use sessions. In production, this should be a long, random value loaded from environment variables, not hardcoded.if 'username' in session: checks if the user is logged in. Accessing session is just like accessing a dict.session['username'] = ... saves data. Flask will automatically serialize this, sign it, and send it as a cookie in the response.session.pop('username', None) removes the key. This effectively logs the user out.
