Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting the expiration time for a cookie in Flask

I'm using the the Python web framework Flask. I use sessions in my app. For my app called main, I've got the setting main.permanent_session_lifetime = timedelta(days=5), so that a user will remain logged in for 5 days after logging in. But even an active user will be logged out after 5 days. I would like the expiration time to reset each time they visit the site, so you get logged out only after 5 days of inactivity. Most sites work this way. How do I do that with Flask?

like image 733
J-bob Avatar asked Nov 04 '13 01:11

J-bob


People also ask

How do I change cookie expiry date?

This can be done easily by adding expires=expirationDate in UTC separated by semicolon from the name=value, as seen in the following example: document. cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC"; document.

Can you set an expiration date and time for a cookie?

You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the 'expires' attribute to a date and time.

How do you handle cookie expiration?

Cookies with an expiration date in the past will be removed from the browser. To remove a cookie, you must set it's set its expiration date in the past. This will signal to the browser that the cookie should be removed.

What is default expiry time for cookies?

The default time for a Cookie to expire is 30 minutes. The default Expires value for a cookie is not a static time, but it creates a Session cookie. This will stay active until the user closes their browser/clears their cookies. You can override this as required.


2 Answers

You can renew the session to the client at each request using a @before_request handler.

Try the following:

@app.before_request
def func():
  session.modified = True
like image 163
Paolo Casciello Avatar answered Oct 16 '22 14:10

Paolo Casciello


Should be enough with:

from datetime import timedelta

# User will be logout after this time of inactivity
PERMANENT_SESSION_LIFETIME = timedelta(minutes=30)
SESSION_REFRESH_EACH_REQUEST = True

https://flask.palletsprojects.com/en/1.1.x/config/

like image 39
GBrian Avatar answered Oct 16 '22 15:10

GBrian