问题描述
我正在尝试在 Flask 应用程序内的 Python 中启动一个新线程.我正在做由请求触发的后台工作,但我不需要等待工作完成来响应请求.
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.
是否可以将这个子威胁中的flask请求设置为进来的请求?原因是,我们对数据库(mongoDB 前面的 mongoengine)查询的 ACL 依赖于请求的用户(它从flask 的请求对象中获取它)来查看他们是否有权访问这些对象,并且由于请求是在子线程中不可用.
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"
推荐答案
从 0.10 版开始,就有了一种支持的方法:http://flask.pocoo.org/docs/api/#flask.copy_current_request_context
Since version 0.10 there is a supported way of doing this: http://flask.pocoo.org/docs/api/#flask.copy_current_request_context
如果您希望 before_request
钩子运行,您必须在装饰函数内部调用 current_app.preprocess_request()
.
If you want the before_request
hooks to run you must call current_app.preprocess_request()
inside of the decorated function.
这篇关于Flask 在启动子线程时抛出“在请求上下文之外工作"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!