【问题标题】:Python flask session not getting stored in generator functionPython烧瓶会话未存储在生成器函数中
【发布时间】:2018-11-15 22:40:50
【问题描述】:

我在我的烧瓶路由之一中使用生成器将输出流式传输到前端,并将值存储在会话变量中,如下所示:

@bp.route('/stream', methods=['GET', 'POST'])
@login_required
def stream():
    def generate():
        if request.method == "POST":
            ...
            ...
            # trying to store a variable to use in another function 
            session['testing'] = "testing"

    return Response(stream_with_context(generate()), mimetype='text/html')

我想在另一个函数中使用这个变量:

@bp.route('/other_func', methods=['GET', 'POST'])
def other_func():
    ...
    ...
    # trying to recieve it here 
    testing = session.get('testing')

    print(testing) # this value is 'None'

我存储在生成器函数中的任何变量都会导致None

我该如何解决这个问题?

【问题讨论】:

  • 您的烧瓶应用配置中是否设置了密钥?
  • @DinkoPehar 是的,它在我的init.py 中,这以前可以工作,添加生成器功能后它停止工作,生成器功能是否会以某种方式影响会话的存储?
  • 如果您在session['testing'] = "testing" 之前尝试session.permanent = True 会怎样?
  • 你确定 generate 函数正在执行 if 语句中的那部分吗?部分 request.method == 'POST' ?
  • @DinkoPehar 我认为它也是如此,因为生成器不存储值并且只迭代一次,我相信我的会话在函数完成后被清除。想办法解决这个问题...

标签: python-3.x session flask


【解决方案1】:

在你的生成器中添加 app.app_context(): 如下:

@bp.route('/stream', methods=['GET', 'POST'])
@login_required
def stream():
    def generate():
        with app.app_context():
            if request.method == "POST":
             ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2018-08-18
    相关资源
    最近更新 更多