Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask permanent session: where to define them?

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.permanent = True, as is mentioned in this question., and the expiration date will be set based on config['PERMANENT_SESSION_LIFETIME'].

I am surprised that session lifetime is defined in config file, yet it is not possible to request the use of permanent sessions through configuration, such as a config['USE_PERMANENT_SESSION'] = True. But so be it.

My question is: if you do want permanent sessions, what is the best place to define them ? Is it in an @app.before_request function as proposed in mentioned question ? But that would mean setting it over again at each request ? It seems that once set, session.permanent remains true till end of session.

Permanent sessions are generally used after sign-in, so maybe the best place to request them is while processing login_user() ? So is the best policy to use volatile session cookies for all anonymous pages, and switch to permanent sessions by doing a session.permanent = True at sign-in ?

And one might want to set a different lifetime depending on whether it is the ordinary session cookie, or the remember_me cookie. What would be the best way to achieve this ?

like image 275
patb Avatar asked Dec 06 '15 13:12

patb


People also ask

How do I create a permanent session in Flask?

In order to use permanent sessions, which will use a cookie with a defined expiration date, one should set session. permanent = True , as is mentioned in this question., and the expiration date will be set based on config['PERMANENT_SESSION_LIFETIME'] .

How do you define a session in Flask?

Flask – Sessions Like Cookie, Session data is stored on client. Session is the time interval when a client logs into a server and logs out of it. The data, which is needed to be held across this session, is stored in the client browser. A session with each client is assigned a Session ID.

What is session permanent?

Session persistence is a method to direct all requests originating from a single logical client to a single backend web server.


1 Answers

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 
like image 194
mikey8989 Avatar answered Sep 23 '22 11:09

mikey8989