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.
Practice
session object?Solution
Step 1: Understand the role of session in Flask
The session object is designed to keep data for a user during their visit, like a temporary storage.Step 2: Compare with other options
Connecting to databases, handling uploads, and rendering templates are done by other Flask features, not session.Final Answer:
To store user-specific data temporarily between requests -> Option AQuick Check:
Session stores user data temporarily [OK]
- Thinking session connects to databases
- Confusing session with template rendering
- Assuming session handles file uploads
Solution
Step 1: Check the correct import statement
The Flask session object is imported directly from flask usingfrom flask import session.Step 2: Verify usage syntax
After import, you can use it like a dictionary:session['user'] = 'Alice'.Final Answer:
from flask import session\nsession['user'] = 'Alice' -> Option CQuick Check:
Import session from flask and assign like dict [OK]
- Trying to import session from flask_session package
- Using wrong import syntax like import session
- Accessing session as flask.session instead of from flask import session
from flask import Flask, session
app = Flask(__name__)
app.secret_key = 'secret'
@app.route('/')
def index():
session['count'] = session.get('count', 0) + 1
return f"Count: {session['count']}"Solution
Step 1: Understand session initialization and increment
The code gets 'count' from session or 0 if not set, then adds 1 and stores it back.Step 2: Determine output on first request
On first visit, 'count' is not in session, so session.get('count', 0) returns 0, then incremented to 1.Final Answer:
Count: 1 -> Option AQuick Check:
First visit count starts at 1 [OK]
- Assuming count starts at 0 output
- Expecting count to be 2 on first visit
- Forgetting to set secret_key causing errors
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def index():
session['user'] = 'Bob'
return f"User: {session['user']}"Solution
Step 1: Check for secret_key setting
Flask sessions requireapp.secret_keyto encrypt session data securely.Step 2: Identify missing secret_key
The code does not setapp.secret_key, so session will raise an error or not work properly.Final Answer:
Missing app.secret_key causing session error -> Option BQuick Check:
Secret key missing breaks session [OK]
- Forgetting to set secret_key
- Assuming session works without secret_key
- Misreading import or decorator syntax
Solution
Step 1: Set session value correctly
Assigning withsession['lang'] = 'en'is correct to store the language.Step 2: Retrieve session value safely
Usingsession.get('lang', 'default')safely gets the value or returns 'default' if missing, avoiding errors.Final Answer:
session['lang'] = 'en'\nlang = session.get('lang', 'default') -> Option DQuick Check:
Use session.get() to avoid KeyError [OK]
- Using session.set() which does not exist
- Accessing wrong key causing KeyError
- Not providing default value when reading session
Ready to prove it?
Pass the test and this pattern moves unknown
