在启动子线程时,Flask抛出'在请求上下文之外工作'

Mat*_*odd 52 python mongoengine flask

我试图在Flask应用程序中的Python中启动一个新线程.我正在做由请求触发的后台工作,但我不需要等待完成工作来响应请求.

是否可以在此次威胁中将烧瓶请求设置为进入的请求?原因是,我们对DB的查询(mongoDB前面的mongoengine)的ACL依赖于请求的用户(它从flask的请求对象中获取)以查看他们是否有权访问这些对象,并且因为请求是在子线程中不可用.

任何想法将不胜感激.

这是我现在如何处理它的伪代码,但它不起作用.

@app.route('/my_endpoint', methods=['POST'])
def my_endpoint_handler():
    #do tracking in sub-thread so we don't hold up the page
    def handle_sub_view(req):
        from flask import request
        request = req
        # Do Expensive work
    thread.start_new_thread(handle_sub_view, (request))
    return "Thanks"
Run Code Online (Sandbox Code Playgroud)

Ale*_*ega 66

将您的线程代码包装test_request_context在一起,以便您可以访问上下文本地:

@app.route('/my_endpoint', methods=['POST'])
def my_endpoint_handler():
    #do tracking in sub-thread so we don't hold up the page
    def handle_sub_view(req):
        with app.test_request_context():
            from flask import request
            request = req
            # Do Expensive work
    thread.start_new_thread(handle_sub_view, (request))
    return "Thanks"
Run Code Online (Sandbox Code Playgroud)

编辑:值得指出的是,该线程将具有与原始请求不同的上下文.在生成线程之前,您需要提取任何有趣的请求数据,例如用户ID.然后,您可以使用ID在子线程中获取(不同的)用户对象.

  • 您可能还想考虑抽象出来 - http://celeryproject.org/我用它来阻止发送电子邮件等操作.好处是您可以使用mongoDB作为后端,因此您不必向堆栈添加任何内容. (2认同)

run*_*alk 30

从版本0.10开始,有一种支持的方法:http://flask.pocoo.org/docs/api/#flask.copy_current_request_context

如果你想让before_request钩子运行,你必须current_app.preprocess_request()在装饰函数内部调用.


jrc*_*jrc 9

正如@runfalk 指出的那样,您需要使用@copy_current_request_context. 这是一个工作代码片段:

import threading

from flask import request, jsonify, copy_current_request_context


@app.route('/foo')
def get_foo():
    @copy_current_request_context
    def foo_main():
        # insert your code here
        print(request.url)

    threading.Thread(target=foo_main).start()

    return jsonify({'status': 'started'})
Run Code Online (Sandbox Code Playgroud)


vim*_*vim 5

您可以复制所需的信息并将其传递给:

@app.route('/my_endpoint', methods=['POST'])
def my_endpoint_handler():
    #do tracking in sub-thread so we don't hold up the page
    def handle_sub_view(data):
        # Use the data in subprocess
    data = request.get_json()  # copy the data
    thread.start_new_thread(handle_sub_view, data)
    return "Thanks"
Run Code Online (Sandbox Code Playgroud)