Jordan Bonser
  • Home
  • CV
  • University Work
    • Second Year Work >
      • Top-Down Shooter
    • Third Year Work >
      • Terrain Analysis Project >
        • Terrain Analysis Tool
        • Game Demonstration
      • Post Processing
      • Android Application - Sports Centre
  • Projects
    • Unity Development >
      • Lerpz Tutorial
      • Dare to be Digital Entry - "Lit"
      • Unity Game
    • Geometry Instancing
    • Road to Eldorado
    • Level Editor
    • OpenGL Work
    • JBEngine
  • Blog
  • Tutorials
    • Flask Session Timeout

Development Blog

Basic Flask Session Timeout on Inactivity

22/5/2016

15 Comments

 
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

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:

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
15 Comments
Roberto Prevato link
14/5/2017 08:45:47 pm

Thanks for the informative post, really clear and to the point. I think this approach works well also when integrating with Azure Active Directory: in an example in Azure-Samples in GitHub, it's shown how to store Azure access token in secure cookie session.

Reply
Jean Paul Goutier
17/7/2017 12:22:35 pm

Where do you put this code?

Reply
Roberto Prevato link
17/7/2017 12:39:04 pm

This code can be placed anywhere, as long as it gets an instance of Flask application. For example, if "foo" was the name of your instance of Flask, then the function decorator would be: "@foo.before_request". The before_request handler can be defined in the same Python module where the instance of application is created, or in a dedicated module (inside a function that receives the instance of application as argument). If these words seem confusing, please see http://flask.pocoo.org/docs/0.12/quickstart/.

Reply
Jordan Bonser link
19/7/2017 08:07:37 am

Thank you for the quick response Roberto, I hadn't even had chance to look myself. Also +1 for linking the documentation :)

Reply
Roberto Prevato
19/7/2017 12:46:33 pm

You're most welcome, Jordan. I found your post really useful. :)

Reply
pax0r
9/8/2017 10:20:42 am

Hi,
Is there a way to have non-pernament session with session-lifetime?
I would like to logout user on (whatever comes first) closing the browser or some time without any activity.

Reply
Jordan Bonser
9/8/2017 10:43:28 am

Hi Paxor,
it's been a while since I have played with Flask but I'm pretty sure as long as you don't use the "Remember me" functionality of Flask-Login then this code will do exactly what you are asking. This code adds a inactivity timeout to a session. if the browser is closed the session will expire anyway.

Reply
Pax0r
9/8/2017 10:58:18 am

Thx, I'll give it a try. I thought that permant_session means that it will not be ended after browser close.

Reply
Tunji
20/10/2018 01:05:54 pm

It helped. Thanks a lot.

However, is it possible the page is redirected to login page automatically when login times out

Reply
Jordan Bonser
20/10/2018 08:05:30 pm

Hi Tunji,

I believe that is already covered by the Flask-Login functionality.

If you decorate any endpoint with @login_required then by default it will redirect you to the login_view when you are not logged in.

See the link below for details on how to supply the login view: https://flask-login.readthedocs.io/en/latest/#customizing-the-login-process

I hope that helps.

Reply
Tunji
22/10/2018 06:49:27 am

Hi Jordan,

Yes, for all of my routes, login is required and I decorated them with login_required from flask-login. However, when the login times out, I wouldn't know until I try to access a page and then be taken to login page.

I was hoping it'd automatically redirect me to login page when it times out.

Steve
16/3/2021 08:58:45 pm

Extremely good post, with simple and clear explanation.

I think in order for the session to "automatically" go back to the login screen upon session expiration (without the user doing something), you would need to set up a keepalive transaction. In each page (except login page), you would need a setInterval() function in the Javascript to periodically make a keepalive REST call to the backend. If that endpoint included the @login_required decorator, then it could send the user back to the log in screen if the session was expired. If still active, then the function would just return 200 OK.

Reply
Freddy Mendoza
23/7/2021 04:25:03 pm

Muy bueno,

funciona muy bien

gracias

Reply
karma
8/9/2021 12:17:03 pm

swada

Reply
Andres
27/5/2022 04:38:25 pm

Hi thanks for your post. I was trying to set the timeout in flask, but it is not working. Each time I make a new request the session expiry field in the database is updating. Is there any reason for that?

Reply



Leave a Reply.

    Archives

    May 2020
    April 2020
    January 2020
    November 2019
    October 2019
    September 2019
    July 2019
    June 2019
    May 2019
    April 2019
    March 2019
    February 2019
    August 2018
    July 2018
    June 2018
    March 2018
    January 2018
    June 2017
    February 2017
    September 2016
    August 2016
    July 2016
    June 2016
    May 2016
    February 2016
    January 2016
    December 2015
    November 2015
    September 2015
    August 2015
    July 2015
    June 2015
    March 2015
    January 2015
    November 2014
    October 2014
    September 2014
    August 2014
    July 2014
    June 2014
    May 2014
    February 2014
    January 2014
    December 2013
    November 2013
    October 2013
    July 2013
    June 2013
    May 2013
    April 2013
    March 2013
    February 2013
    January 2013
    December 2012
    October 2012
    September 2012
    August 2012
    July 2012
    June 2012
    May 2012

    Categories

    All
    2D
    3rd Year Project
    Agile
    Android
    Angular
    Animation
    API
    Apple
    Apps
    Arden
    Async
    Awesomium
    C#
    CI/CD
    Clean Code
    CMake
    Cocos2d-x
    Colour Match
    Compilers
    Cross Compiling
    Cross-Compiling
    Databases
    Design
    Development Tools
    Docker
    Electronics
    Examples
    Flask
    Flask-Login
    Fmod
    Game Development
    Godot
    GUI
    Hackathon
    Hacktoberfest
    Hardware
    Home Life
    IBM
    Inspired Gaming
    Instancing
    Ios
    Javascript
    Jbengine
    Kata
    Level Editor
    Linux
    Microsoft
    Mobile Development
    Monogame
    Moodster
    Motivation
    Networking
    Objective C
    Opengl
    Open Source
    Organisation
    Physics
    Physx
    Pi
    Planning
    Post Mortem
    PyGame
    Python
    Quart
    Quasar
    RakNet
    React
    Road To Eldoarado
    Scripting
    Scrum Master
    Sessions
    Session Timeout
    Social
    Sound
    Space Invaders
    Squash Game
    Squash Game
    Streaming
    TDD
    Team Leading
    Test
    Test Driven Development
    Travis
    Unity
    Unity Development
    VSCode
    Vulkan
    Web Applications
    Worklife
    WSL
    XML
    XNA / C#

    RSS Feed

Powered by Create your own unique website with customizable templates.
  • Home
  • CV
  • University Work
    • Second Year Work >
      • Top-Down Shooter
    • Third Year Work >
      • Terrain Analysis Project >
        • Terrain Analysis Tool
        • Game Demonstration
      • Post Processing
      • Android Application - Sports Centre
  • Projects
    • Unity Development >
      • Lerpz Tutorial
      • Dare to be Digital Entry - "Lit"
      • Unity Game
    • Geometry Instancing
    • Road to Eldorado
    • Level Editor
    • OpenGL Work
    • JBEngine
  • Blog
  • Tutorials
    • Flask Session Timeout