techmonk techmonk - 1 year ago 172
Python Question

Flask session variable not persisting between requests

Using the app below and Flask 0.11.1, I navigated to the routes associated with the following function calls, with the given results:

  • create(): '1,2,3' # OK

  • remove(1) : '2,3' # OK

  • remove(2) : '1,3' # expected '3'

  • maintain(): '1,2,3' # expected '1,3' or '3'


from flask import Flask, session

app = Flask(__name__)

def create():
session['list'] = ['1','2','3']
return ",".join(session['list'])

def maintain():
return ",".join(session['list'])

def remove(id):
return ",".join(session['list'])

if __name__ == '__main__':
app.secret_key = "123"

This question is similar in theme to this question, this, and this one, but I'm setting the secret key and not regenerating it, and my variable is certainly not larger than the 4096 bytes allowed for cookies. Perhaps I'm missing some more basic understanding about Flask session variables?

Answer Source

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:

def remove(id):
    val = session['list']
    session['list'] = val
    return ",".join(session['list'])

…and same with other changes, or you might try to set session.modified = True yourself instead of triggering the detection.