Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask session forgets entry between requests

I'm using the latest Flask/Werkzeug (Flask 0.9) client-side sessions to persist information between requests. The session is not set to be persistent (as I'm fine with the cookie being deleted when the browser is closed).

My problem is as follows:

I use some server-side code to fill the Flask session variable with an entry. After this, the Session variable looks something like this:

<SecureCookieSession {u'items': SOMENOTVERYIMPORTANTDICTIONARY}, '_fresh': True, 'user_id': u'1', 'csrf': '0aef1995cdf2cxx0233fdf3321d17fc7267f3b32', '_id': 'someUNIQUEcode'}*>

I use this information to render a page that performs a GET request (through JQuery) to the same Flask application, but suddenly the dictionary containing the 'items' entry in the session is gone:

<SecureCookieSession {'_fresh': True, 'user_id': u'1', 'csrf': '0aef1995cdf2cxx0233fdf3321d17fc7267f3b32', '_id': 'someUNIQUEcode'}>

I did some searching around, and thought that it may be related to the fact that I'm testing on localhost (127.0.0.1 is not the same as localhost). I fixed my hosts file and added a 'dev.localhost' entry to make sure that all requests are from the same host.

Also, the developer pane of my browser (Chrome) shows exactly the same identifiers for the session cookies being sent to the server.

Also, setting session.modified = True does not help.

The only thing that changes between requests is

__utmb=122666782.18.10.1363877633

for the first request (the one that populates the items entry) vs. the second request

__utmb=122666782.19.10.1363877633

Thinking that it still may be an Ajax-related-thing. I tested the contents of the session variable after a straightforward page reload: the items entry is still gone from the session.

Any help would be greatly appreciated.

like image 416
RJH Avatar asked Mar 21 '13 16:03

RJH


1 Answers

It turns out that the cookie being sent back to the client (Chrome) exceeds the 4096 bytes limit for cookie size. Apparently Django uses server-side sessions by default, which made this problem only appear when I moved my code to Flask. Using server side sessions in Flask such as in flask-kvsession and others should fix the issue.

like image 63
RJH Avatar answered Sep 28 '22 07:09

RJH