In Flask, sessions help keep track of user information across requests. Why is it important that session data is stored on the server side rather than only in the browser?
Think about what could happen if users could change their own session data.
Sessions store data on the server to keep it safe and prevent tampering. If data was only on the client, users could change it and cause errors or security issues.
Consider a Flask app using sessions to track user login status. What happens to the session data if the user closes their browser and then reopens the site?
Think about how cookies control session lifetime.
Session cookies usually expire when the browser closes unless set to persist. Without a persistent cookie, the session ID is lost, so the server cannot recognize the user and requires login again.
Which option correctly sets a session variable named 'username' to 'alice' in a Flask route?
from flask import Flask, session app = Flask(__name__) app.secret_key = 'secret' @app.route('/') def index(): # Set session variable here pass return 'Done'
Remember how to use dictionary syntax in Python.
Flask sessions behave like dictionaries. You set values using square brackets and assignment, like session['key'] = value.
Given this Flask route, what will be the output when visiting '/count' three times in a row?
from flask import Flask, session app = Flask(__name__) app.secret_key = 'secret' @app.route('/count') def count(): if 'visits' in session: session['visits'] += 1 else: session['visits'] = 1 return f"Visit number: {session['visits']}"
Think about how session data persists between requests.
The session keeps track of 'visits' and increments it each time the route is accessed, so the output counts up on each visit.
Examine this Flask route code. Why does it raise a RuntimeError: Working outside of request context when trying to access session?
from flask import Flask, session app = Flask(__name__) app.secret_key = 'secret' user_session = session @app.route('/') def index(): user_session['logged_in'] = True return 'Logged in'
Think about when Flask creates the session object.
The session object is only available during a request. Assigning it outside a route causes the error because no request context exists yet.