【问题标题】:Flask start new thread - RuntimeError: Working outside of request context烧瓶启动新线程 - RuntimeError:在请求上下文之外工作
【发布时间】:2018-11-09 02:02:06
【问题描述】:

我正在使用烧瓶来运行我已经与保存用户 ID 和其他信息的会话相关的长进程。我尝试通过以下两种方法使用新线程,但仍然出现错误“RuntimeError:在请求上下文之外工作。”

方法一

import threading
Thread(target=lambda: fn(**args)).start()

方法二

import thread
thread.start_new_thread(fn, (), args)

【问题讨论】:

    标签: python multithreading flask


    【解决方案1】:

    要在线程内使用会话,您必须使用 copy_current_request_context 从桥启动该线程

    from flask import copy_current_request_context
    @copy_current_request_context
    def ctx_bridge():
        fn(**args)
    Thread(target=ctx_bridge).start()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多