我正试图在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"
将线程代码封装在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"
编辑:值得指出的是,线程将具有与原始请求不同的上下文。在生成线程之前,您需要提取任何感兴趣的请求数据,例如用户ID。然后,您可以使用ID在子线程中获取一个(不同的)用户对象。
由于版本0.10,因此有一种支持的方法:http://flask.pocoo.org/docs/api/#flask.copy_current_request_context
如果要运行before_request
挂钩,则必须在装饰函数内部调用current_app.preprocess_request()
。
@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'})
您可以复制所需信息并将其传递:
@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"
更干净的方法是使用Flask内置的执行器来包装应用程序上下文,请参阅https://flask-executor.readthedocs.io/en/latest/