Flask session variable not persisting between requests

I was having this same problem and I found out that my changes in the session were not persisting because my data was too big.

From here:

"By default, there isn't much difference between cookies and client-based sessions in Flask. As a result, the client-based sessions suffer from the same drawbacks the cookies have like:

  • Can't store sensitive data like passwords.
  • Additional payload on every request.
  • Can't store data more than 4KB.
  • Limit on the number of cookie per website and so on.

If your data is larger than 4KB, a server-side Session is needed. Have a look at Flask-Session.


Flask uses a CallbackDict to track modifications to sessions.

It will only register modifications when you set or delete a key. Here, you modify the values in place, which it will not detect. Try this:

@app.route('/r/<int:id>')
def remove(id):
    val = session['list']
    val.remove(str(id))
    session['list'] = val
    return ",".join(session['list'])

…and same with other changes.

Alternatively, you can flag the modification yourself instead of triggering the detection:

@app.route('/r/<int:id>')
def remove(id):
    session['list'].remove(str(id))
    session.modified = True
    return ",".join(session['list'])

From the doc:

Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the [modified attribute] to True yourself.

Try:

session['list'].remove(str(id))
session.modified = True