Session lifetime controls how long a user's session stays active before it expires. This helps keep user data safe and improves app behavior.
Session lifetime in Flask
from flask import Flask, session from datetime import timedelta app = Flask(__name__) app.secret_key = 'your_secret_key' # Set session lifetime app.permanent_session_lifetime = timedelta(minutes=30) @app.route('/') def index(): session.permanent = True # Make session permanent to use lifetime session['user'] = 'Alice' return 'Session is set with 30 minutes lifetime'
Use app.permanent_session_lifetime to set how long sessions last.
Set session.permanent = True inside a route to apply the lifetime to that session.
app.permanent_session_lifetime = timedelta(hours=1) session.permanent = True
app.permanent_session_lifetime = timedelta(days=7) session.permanent = True
session.permanent = FalseThis Flask app sets a session lifetime of 10 seconds. When you visit '/', it starts a session for user 'Bob'. Visiting '/check' shows the current session user or says no active session if expired.
from flask import Flask, session from datetime import timedelta app = Flask(__name__) app.secret_key = 'secret123' app.permanent_session_lifetime = timedelta(seconds=10) @app.route('/') def index(): session.permanent = True session['username'] = 'Bob' return 'Session started for Bob with 10 seconds lifetime.' @app.route('/check') def check(): user = session.get('username', 'No active session') return f'Current session user: {user}' if __name__ == '__main__': app.run(debug=True)
Sessions with permanent = False expire when the browser closes.
Make sure to set a secret_key for sessions to work securely.
Session lifetime helps balance user convenience and security.
Session lifetime controls how long user data stays in a session.
Set app.permanent_session_lifetime to define duration.
Use session.permanent = True to apply the lifetime.
Practice
session.permanent = True in a Flask app do?Solution
Step 1: Understand session permanence in Flask
Settingsession.permanent = Truetells Flask to keep the session alive for a set duration instead of ending it when the browser closes.Step 2: Connect to
The session will then use the time defined inpermanent_session_lifetimeapp.permanent_session_lifetimeto decide how long it lasts.Final Answer:
It makes the session use thepermanent_session_lifetimeduration. -> Option AQuick Check:
session.permanent = True means use permanent_session_lifetime [OK]
- Thinking session.permanent deletes session immediately
- Confusing permanent with disabling cookies
- Assuming session resets lifetime to zero
Solution
Step 1: Identify the correct Flask attribute for session lifetime
The Flask app usesapp.permanent_session_lifetimeto set how long permanent sessions last.Step 2: Use the correct data type
This value must be atimedeltaobject from Python'sdatetimemodule, e.g.,timedelta(minutes=30).Final Answer:
app.permanent_session_lifetime = timedelta(minutes=30) -> Option AQuick Check:
Use app.permanent_session_lifetime with timedelta [OK]
- Setting session.lifetime instead of app.permanent_session_lifetime
- Assigning integer instead of timedelta
- Using session.permanent_session_lifetime which does not exist
session.permanent = True and app.permanent_session_lifetime = timedelta(hours=1)?
from flask import Flask, session
from datetime import timedelta
app = Flask(__name__)
app.secret_key = 'secret'
app.permanent_session_lifetime = timedelta(hours=1)
@app.route('/')
def index():
session.permanent = True
session['user'] = 'Alice'
return 'Session set'Solution
Step 1: Check the session permanence setting
The code setssession.permanent = True, so the session uses the app's permanent lifetime.Step 2: Identify the permanent session lifetime
The app setsapp.permanent_session_lifetime = timedelta(hours=1), so the session lasts 1 hour.Final Answer:
The session will last 1 hour before expiring. -> Option DQuick Check:
session.permanent True + app.permanent_session_lifetime = 1 hour [OK]
- Assuming session expires immediately after request
- Thinking session lasts until browser closes when permanent=True
- Assuming default 24 hours without setting
from flask import Flask, session
from datetime import timedelta
app = Flask(__name__)
app.secret_key = 'secret'
app.permanent_session_lifetime = timedelta(hours=1)
@app.route('/')
def index():
session['user'] = 'Bob'
return 'Session set'Solution
Step 1: Check if session is marked permanent
The code setssession['user']but does not setsession.permanent = True.Step 2: Understand session expiration behavior
Withoutsession.permanent = True, the session lasts only until the browser closes, ignoringpermanent_session_lifetime.Final Answer:
You forgot to setsession.permanent = True. -> Option CQuick Check:
session.permanent must be True to use permanent_session_lifetime [OK]
- Assuming setting session key alone applies lifetime
- Using app.session_lifetime which is invalid
- Thinking secret key affects session expiration
- Calling non-existent session.save() method
Solution
Step 1: Set the permanent session lifetime correctly
Useapp.permanent_session_lifetime = timedelta(hours=2)to define 2 hours for permanent sessions.Step 2: Control session permanence based on user choice
Inside the login route, check if the user selected 'Remember me'. If yes, setsession.permanent = True, else set it to False.Step 3: Assign the user to session and return response
Store the username in session and return a confirmation message.Final Answer:
app.permanent_session_lifetime = timedelta(hours=2) @app.route('/login', methods=['POST']) def login(): if request.form.get('remember') == 'yes': session.permanent = True else: session.permanent = False session['user'] = request.form['username'] return 'Logged in' -> Option BQuick Check:
Conditional session.permanent with app.permanent_session_lifetime set [OK]
- Not setting session.permanent based on user input
- Using app.session_lifetime instead of app.permanent_session_lifetime
- Always setting session.permanent True ignoring user choice
Ready to prove it?
Pass the test and this pattern moves unknown
