在flask中返回即时响应,但在新线程中完成处理 [英] Returning an immediate response in flask, but finishing the processing in a new thread
问题描述
我有一个从10秒开始的过程,但是在10秒之后,我不需要将信息返回给用户,而是将其记录在dynamoDB上,这就是为什么我希望用户不必等待10秒相反,我希望在发布请求后立即获得成功"响应.
I have a process from 10 seconds, but after the 10 seconds, I don't need to return the information to the user but write it down on a dynamoDB, that's why I would like the user doesn't have to wait 10 seconds. Instead, I would like an immediate "Success" response after the post request.
我阅读了几篇文章,并在这带有拆解回调,但没有示例.
I read a couple of posts and in this one, the answer was with a Teardown Callback, but there wasn't an example.
然后,我阅读了此,但是它没有帮助我与我的问题.
I read then this, but it doesn't help me with my problem.
我当然阅读了 teardown-callbacks 和
I read of course teardown-callbacks and this pattern but I don't know how I could use it another way.
我的代码如下:
@app.route('/ocr/read_image', methods=['POST'])
def get_text():
return jsonify('Success')
@app.teardown_request
def teardown_request(response):
time.sleep(10)
它实际上返回成功"消息,但仅在10秒之后.
It actually returns the "Success" Message but just after the 10 seconds.
有没有办法在10秒之前返回成功"消息?
Is there a way to return the "Succes" Message before the 10 seconds?
我一直在阅读,芹菜也许是可行的,但如果可以的话,我会尽量避免.
I've been reading that it's maybe possible with celery but I would love avoid it if I can.
有人知道怎么做吗?
推荐答案
正如Ardaglio所说,最好的方法是使用多线程.
As Ardaglio said, the best way was using multithreading.
我没有使用Celery,因为我认为它非常复杂,而且我的问题也很容易解决.
I didn't use Celery, because I think it's pretty complicated and my problem is quite easy for it.
所以,我正在使用线程:
So, I'm using Thread:
from threading import Thread
@app.route('/ocr/read_image', methods=['POST'])
def get_text():
Thread(target=continue_processing).start()
return jsonify('Success')
def continue_processing():
time.sleep(10)
print('Hi')
但是,您必须小心.我将Keras与Tensorflow作为后端一起使用,如果使用它,则会出现一个很好的值错误 ValueError:Tensor Tensor()不是此图的元素.
But, you gotta be careful. I'm using Keras with Tensorflow as Backend, and if you use it so, you will have a nice value error ValueError: Tensor Tensor()is not an element of this graph.
因此,为了避免在线程内出现它,您必须在创建模型后保存图:
So, to avoid it inside a Thread, you've to save the Graph after the model is made:
GRAPH = tf.get_default_graph()
,然后您必须通过以下方式在异步过程中使用它:
and then you've to use it inside the asynchron process this way:
with GRAPH.as_default():
do something with your model
希望它可以对某人有所帮助.
Hope it could be help someone.
这篇关于在flask中返回即时响应,但在新线程中完成处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!