当启动子线程时,引发瓶颈“在请求上下文之外工作” [英] Flask throwing 'working outside of request context' when starting sub thread

查看:231
本文介绍了当启动子线程时,引发瓶颈“在请求上下文之外工作”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



是否有可能在这个子威胁设置烧瓶请求来到的请求?原因是,我们对我们的DB(mongoDB前的mongoengine)的查询的ACL依赖于请求的用户(它从瓶子的请求对象中抓取它)来查看它们是否可以访问这些对象,并且由于请求是没有在子线程中可用。



任何想法都将不胜感激。



这里是伪代码

  @ app.route('/ my_endpoint',methods = [' POST'])
def my_endpoint_handler():
#在子线程中跟踪,所以我们不占用页面
def flask_sub_view(req):$ b $ from flask import请求
请求=请求
#做昂贵的工作
thread.start_new_thread(handle_sub_view,(request))
returnThanks


解决方案在 test_request_context 中包装你的线程代码,访问 context locals
$ b

  @ app.route(' / my_endpoint',methods = ['POST'])
def my_endpoint_handler():
#在子线程中跟踪,所以我们不占用页面
def handle_sub_view(req) :
with app.test_request_context():
来自瓶子的导入请求
request =请求
#做昂贵的工作
thread.start_new_thread(handle_sub_view,(request))
returnThanks

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


I am trying to start a new thread in Python inside of a Flask application. I am doing background work that gets triggered by the request, but I don't need to wait for the work to be done to respond to the request.

Is it possible to set the flask request in this sub-threat to the request that came in? Reason being, our ACL on our queries to our DB (mongoengine in front of mongoDB) relies on the request's user (it grabs it from flask's request object) to see if they have access to the objects, and its blowing up because the request is not available in the sub-thread.

Any thoughts would be much appreciated.

Here's pseudo code of how I am handling it now, but it is not working.

@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"

解决方案

Wrap your thread code in a test_request_context so you have access to context locals:

@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"

Edit: it's worth pointing out that the thread will have a different context than the original request. You need to extract any interesting request data, such as the user ID, before spawning the thread. You can then grab a (different) user object in the sub-thread using the ID.

这篇关于当启动子线程时,引发瓶颈“在请求上下文之外工作”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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