Is there an easy way to make sessions timeout in flask?

Viewed 105584

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 Answers

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)
Related