Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store User's Data for Session in Flask?

I'm creating a Flask application that requires each request to use some data that a user has passed to the application to initialize their session. Once they have passed that data and initialized the session, I'd like to re-use that data over and over until their session is done to fill requests without them having to pass the data for each request.

I can't seem to figure out the best way to do this. Storing it in the session variable doesn't work because that data just gets sent back to the user and then its the same as just passing it every request. Storing the data in a database doesn't seem like the right choice because I need to throw it away at the end of the session, and I don't see any decorator to implement for when a session expires...so I'm afraid my database will just end up filling up with all of these data that come from initialization and no guaranteed way to remove them at the end of a session.

Any suggestions?

like image 617
Roshmaster Avatar asked Jul 17 '17 21:07

Roshmaster


1 Answers

You have two options here: a session stored on the client, or a session stored on the server.

To store it on the server, you need a data-store. If your app ever has to scale to any extent (including multiple uwsgi workers), you will have to use a distributed store. If you have redis, that would be the best choice. See the Flask-Session example posted by Simon Fraser in the comments to do this. It will handle storing the session object in your database and fetching values from it when needed. It handles a large number of backends as well, so whatever database you have will probably work with it out of the box.

If you don't want to use a backend session, you have to use a client session. This is done by setting a cookie- cookies are automatically attached to most requests the browser sends to your site, so values that you store on the cookie will usually come back to you. (this is how facebook remembers who you are without you logging in on every page. In fact, it is how the Flask-Session keeps track of WHICH session to restore!). In order for this to be reliable, you have to sign the cookie so the user can't modify the values- Flask can handle this for you with the built in Session, or you can use a better crypto library as described Here. If you don't want the user to be able to see the values, or if you have a lot of data to store (the maximum size of a cookie is limited), you will have to use the server side version of all of this.

like image 116
Paul Becotte Avatar answered Sep 19 '22 05:09

Paul Becotte