Consider a Flask app where the secret_key is not configured. What will happen when you try to use sessions?
from flask import Flask, session app = Flask(__name__) @app.route('/') def index(): session['user'] = 'Alice' return 'Session set!' if __name__ == '__main__': app.run()
Think about what Flask requires to sign session cookies.
Flask needs a secret key to sign session cookies. Without it, Flask raises a RuntimeError when you try to use sessions.
Choose the correct way to set a secret key for a Flask app.
from flask import Flask app = Flask(__name__) # Set secret key here
Flask configuration keys are usually uppercase strings.
The correct way is to set app.config['SECRET_KEY']. The attribute app.secret_key also works as a convenience property, but set_secret_key or secretKey do not exist.
Given a Flask app that sets a new random secret key on every request, what happens to the session data?
from flask import Flask, session import os app = Flask(__name__) @app.before_request def set_key(): app.config['SECRET_KEY'] = os.urandom(16) @app.route('/') def index(): session['count'] = session.get('count', 0) + 1 return f"Count: {session['count']}" if __name__ == '__main__': app.run()
Think about how Flask uses the secret key to sign session cookies.
Changing the secret key invalidates previous session cookies, so the session data resets each time.
Review the code below. The session data does not persist between requests. What is the cause?
from flask import Flask, session app = Flask(__name__) app.config['SECRET_KEY'] = 'abc123' @app.route('/') def index(): session['visits'] = session.get('visits', 0) + 1 return f"Visits: {session['visits']}" if __name__ == '__main__': app.run(debug=True, use_reloader=True)
Consider what happens when Flask reloads the app in debug mode.
When using use_reloader=True, Flask restarts the app process, which can reset the secret key if set dynamically. Here it is static, but the reloader causes multiple app instances, confusing session persistence.
Choose the best explanation for why Flask's SECRET_KEY must be kept secret and hard to guess.
Think about what the secret key is used for in Flask sessions.
The secret key is used to cryptographically sign session cookies. If it is guessable, attackers can forge cookies and impersonate users.