Flask - Session Duration
by
Jeremy Canfield |
Updated: June 17 2023
| Flask articles
By default, sessions are volatile, which means the session cookie is set to expire when browser closes. Sessions can be set to permanent so that the session cookie remains even if the user closes their web browser. Almost always, session.permanent is used in conjunection with app.config['PERMANENT_SESSION_LIFETIME'] in __init__.py to see the expiration time of the browser cookie.
In your controller (__init__.py) set the PERMANENT_SESSION_LIFETIME
from flask import Flask
from datetime import timedelta
def app():
app = Flask(__name__)
# In this example, sessions will expire after 86400 seconds (1 day)
app.config['PERMANENT_SESSION_LIFETIME'] = 86400
# Or using timedelta hours
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=24)
# Or using timedelta days
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)
return app
Then set session.permanent and session.modified in your view (views.py in this example).
- session.permanent = True is used to let Flask know that you want the session to expire.
- session.modified = True is used to keep the session active while the user remains active
from flask import Blueprint, render_template, session, app
from flask_login import login_user, login_required, logout_user, current_user
from datetime import datetime
views = Blueprint('views', __name__)
@auth.before_request
def make_session_permanent():
session.permanent = True
session.modified = True
To validate this is working as expected, you can view the cookie that gets created, and created vs. expires should match PERMANENT_SESSION_LIFETIME.
Did you find this article helpful?
If so, consider buying me a coffee over at