How to Make Sessions Timeout in Flask

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

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.

Flask permanent session: where to define them?

I'm surprised no on has answered this question. It seems like there should be some type of config variable SESSION_PERMANENT = True. But unfortunately there isn't. As you mentioned this is the best way to do it.

@app.before_request
def make_session_permanent():
session.permanent = True

Flask Server-Side Session Expiration

I simply ended up adding the session-creation-date to the session store, and then I check the duration between this date and the current date.

Flask session log out and redirect to login page

When I read the documents of the Flask-Login package, i saw a few things. When creating your Flask application, you also need to create a login manager.

login_manager = LoginManager()

A login_view variable in LoginManager class caught my attention. The details include the following explanation:

The name of the view to redirect to when the user needs to log in. (This can be an absolute URL as well, if your authentication machinery is external to your application.)

Actually, after you create a LoginManager object,

login_manager.login_view = 'your login view'

You should specify your login page. Finally,
Once the actual application object has been created, you can configure it for login with:

login_manager.init_app(app)

After doing these, any unauthorized calls to every method you use @login_required annotation will be sent to the page you have pointed out with login_view.

I also developed a simple application. You can review this application from here. I tested it and working without any problems.

I hope it helps you.



Related Topics



Leave a reply



Submit