Flask Session Timeout
I am going to give a small example about how to get session timeout to work for Flask while using the Flask-Login extension.
I have read a few stack overflow posts that show how to do this in pieces but I wanted to summarise this into one example.
Here is the @app.before_request function that will allow you to have session timeout:
I have read a few stack overflow posts that show how to do this in pieces but I wanted to summarise this into one example.
Here is the @app.before_request function that will allow you to have session timeout:
import datetime
import flask
import flask_login
@app.before_request
def before_request():
flask.session.permanent = True
app.permanent_session_lifetime = datetime.timedelta(minutes=20)
flask.session.modified = True
flask.g.user = flask_login.current_user
The flask.session.premanent flag and the app.permanent_session_lifetime allow Flask to know that you want the session to expire. If left with only these two then the session will expire every 20 minutes regardless of whether the user has been active. Realistically you would want the session to expire after 20 minutes of inactivity, which is what the flask.session.modified flag is for. Each time there is a request the flag gets set to True which effectively resets the session timeout timer. The final line retrieves the logged in user from flask_login and sets the Flask global user so that it can be used by the Jinja templates.
As I said that this was to be used with the Flask-Login extension I wanted to point out something that could potentially catch you out. Flask-Login has a "remember me" functionality that is set at login time, the use of this functionality can mess up the session timeout and make it appear as though it does not work. To avoid this you need to look at the login code and ensure that the remember flag is not set to True:
As I said that this was to be used with the Flask-Login extension I wanted to point out something that could potentially catch you out. Flask-Login has a "remember me" functionality that is set at login time, the use of this functionality can mess up the session timeout and make it appear as though it does not work. To avoid this you need to look at the login code and ensure that the remember flag is not set to True:
flask_login.login_user(user, remember=False)
If you want to use the "remember me" functionality then you may need to look into ensuring that the remember me cookie duration is changed but that is out of the scope of this example.
Hope that helps,
Thanks
Originally from my blog: Flask Session Timeout
Hope that helps,
Thanks
Originally from my blog: Flask Session Timeout