This assumes you are already familiar with Flask Sessions. If not, check out my article FreeKB - Flask - Getting Started with Sessions.
By default, sessions are set as permanent.
- Permanent session: A cookie is stored in the browser and not deleted until it expires
- Non-permanent session: A cookie is stored in the browser and is deleted when the browser or tab is closed
PERMANENT_SESSION_LIFETIME can be set in __init__.py. The session will expire when PERMANENT_SESSION_LIFETIME has been reached. In this example, the session lifetime is 14400 seconds (4 hours).
from flask import Flask
from datetime import timedelta
def myapp():
app = Flask(__name__)
app.config['SECRET_KEY'] = "akDFJ34mdfsYMH567sdf" # this must be set in order to use sessions
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
session.permanent can be used to set a specific session as permanent or non-permanent. This will take precedence (override) SESSION_PERMANENT in __init__.py.
from flask import Blueprint, render_template, session
views = Blueprint('routes_home', __name__)
@views.route('/')
def home():
session.permanent = False
session["foo"] = "bar"
return render_template('home.html')
Or you can use before_request to set session.permanent for all routes in your view.
from flask import Blueprint, render_template, session
views = Blueprint('routes_home', __name__)
@views.before_request
def make_session_permanent():
session.permanent = True
@views.route('/')
def home():
session["foo"] = "bar"
return render_template('home.html')
Be careful to not use session.clear() as this will remove the cookies from the users browser.
from flask import Blueprint, render_template, session
views = Blueprint('routes_home', __name__)
@views.route('/')
def home():
session.permanent = False
session["foo"] = "bar"
session.clear()
return render_template('home.html')
To validate this is working as expected, you can view the cookie that gets created.
- If session.permanent is set to True then "Expires" should match PERMANENT_SESSION_LIFETIME
- If session.permanent is set to False then "Expires" should be "When the browsing session ends" (this is the default if session permanent has not been defined)
Did you find this article helpful?
If so, consider buying me a coffee over at