Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 600
verrochio Avatar asked Aug 02 '12 17:08

verrochio


People also ask

How long do Flask sessions last?

Default session lifetime is 31 days, user need to specify the login refresh view in case of timeout. Above line will force user to re-login every 5 minutes.

How do I end a session in Flask?

There is no way to clear session or anything. One must simply change the app. config["SECRET_KEY"] and the contents in session dictionary will get erased.

What is session permanent in Flask?

By default, Flask uses volatile sessions, which means the session cookie is set to expire when browser closes. In order to use permanent sessions, which will use a cookie with a defined expiration date, one should set session.


2 Answers

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.

like image 99
codegeek Avatar answered Sep 26 '22 01:09

codegeek


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 
like image 44
tinyhare Avatar answered Sep 24 '22 01:09

tinyhare