Flask会话变量不会在请求之间持续 [英] Flask session variable not persisting between requests

查看:177
本文介绍了Flask会话变量不会在请求之间持续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用下面的应用程序和Flask 0.11.1,我导航到与以下函数调用相关的路由,并给出了结果:


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

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

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


 

  from flask import Flask ,session 
$ b $ app = Flask(__ name__)

@ app.route('/')
def create():
session ['list '] = ['1','2','3']
return,。join(session ['list'])

@ app.route('/ m ')
def maintain():
return,。join(session ['list'])

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

if __name__ =='__main__':
app.secret_key =123
app。 run()

这个问题与这个问题,和这一个,但我设置密钥,不重新生成它,我的变量当然不会超过cookie允许的4096个字节。也许我错过了对Flask会话变量的一些更基本的了解?

Flask使用 CallbackDict 来跟踪对会话的修改。



只有在设置或删除密钥时才会注册修改。在这里,您可以修改不会检测到的值。试试这个:
$ b $ pre $ @ app.route('/ r /< int:id>')
def remove (id):
val = session ['list']
val.remove(str(id))
session ['list'] = val
return, join(session ['list'])

...和其他更改一样,或者您可以尝试设置 session.modified = True ,而不是触发检测。

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__)

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

@app.route('/m')
def maintain():
    return ",".join(session['list'])

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

if __name__ == '__main__':
    app.secret_key = "123"
    app.run()

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?

解决方案

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, or you might try to set session.modified = True yourself instead of triggering the detection.

这篇关于Flask会话变量不会在请求之间持续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆