104

I'm building a website with flask where users have accounts and are able to login. I'm using flask-principal for the loging in part and the role management. Is there a way of making the user's session expire after say 5 minutes or 10 minutes? I was not able to find that in flask documentation or, flask-principal's documentation.

I thought of a way of doing it by hand, set a variable server-side with a time tag at the moment of login and at the next action the user takes, the server verifies the time-delta on that timestamp and deletes the session.

3
  • Do you want expire user session after inactivity of 5 or 10 minutes or simply expire irrespective of activity level?
    – codecool
    Aug 3, 2012 at 13:53
  • for inactivity i will have to implement that. just to expire when the browser is closed, or 24 hours. It does not expire at all right now.
    – verrochio
    Aug 4, 2012 at 14:40
  • 3
    To make a session expire relative to activity: stackoverflow.com/questions/19760486/…
    – zengr
    Dec 22, 2013 at 18:29

3 Answers 3

159

flask sessions expire once you close the browser unless you have a permanent session. You can possibly try the following:

from datetime import timedelta
from flask import session, app

@app.before_request
def make_session_permanent():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=5)

By default in Flask, permanent_session_lifetime is set to 31 days.

14
  • 18
    I believe it is also true that your session will be reset if you change your app.secret_key and restart the server.
    – John
    Mar 24, 2013 at 22:27
  • 19
    session.permanent is False by default: flask.pocoo.org/docs/api/#flask.session.permanent Jun 11, 2014 at 18:13
  • 1
    Do you know what gets called when the permanent_session_lifetime expires?
    – ramu
    Jun 30, 2015 at 22:11
  • 6
    What is the reason of using before_request here instead of before_first_request?
    – srctaha
    Jan 16, 2017 at 1:41
  • 2
    This is working perfectly! Any suggestion on how we can flash a message when the session expires? Aug 11, 2017 at 23:37
61

Yes, We should set

session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)

But I don't think it should be set at app.before_request, This will lead to set them too may times.

The permanent_session_lifetime is a Basics Configuration, so it should be set at you configure the app:

 from datetime import timedelta
 app = Flask(__name__)
 app.config['SECRET_KEY'] = 'xxxxxxxxx'
 app.config['PERMANENT_SESSION_LIFETIME'] =  timedelta(minutes=5)

The session will created for each client, seperated from other clients. So, I think the best place to set session.permanent is when you login():

@app.route('/login', methods=['GET', 'POST'])
def login():
    #After Verify the validity of username and password
    session.permanent = True
4
  • 1
    For Apache-Airflow (which uses Flask) setting this in github.com/apache/incubator-airflow/blob/master/airflow/contrib/… did not work for me. Sep 20, 2018 at 0:29
  • 1
    Update the link in the answer to the latest version: Basics Configuration
    – Wavesailor
    Feb 5, 2019 at 18:32
  • 1
    I use flask session with rooms and broadcasting etc. above solution however did not work for me. I would expect that after 5min the user is directly logged out and redirected to login page .... is this possible with permanent session? or Do I have to achieve this using db and storing the login date?
    – sqp_125
    Jul 31, 2020 at 15:45
  • Is it possible to set session lifetime per each session? Eg. I have different user types and I want admin users to have a session valid for 1 hour, and the rest for 24 hours.
    – umat
    Oct 10, 2022 at 10:01
4

Using a slight modification on CodeGeek's answer, the decorator @before_first_request is enough to get flask to "remember" the session timeout. @before_request runs before EACH request, which is not necessary. I've tested this with different timeouts and it works.

The calls are explained here.

from datetime import timedelta
from flask import session, app

@app.before_first_request  # runs before FIRST request (only once)
def make_session_permanent():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=5)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.