Flask session variable not persisting between requests

后端 未结 2 486
抹茶落季
抹茶落季 2020-12-29 11:14

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\'
相关标签:
2条回答
  • 2020-12-29 11:29

    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
    
    0 讨论(0)
  • 2020-12-29 11:36

    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'])
    
    0 讨论(0)
提交回复
热议问题