带有后台线程的烧瓶应用程序 [英] flask application with background threads
问题描述
我正在创建一个 Flask 应用程序,对于一个请求,我需要运行一些不需要等待 UI 的长时间运行的作业.我将创建一个线程并向 UI 发送消息.该线程将计算并更新数据库.但是,UI 在提交时会看到一条消息.下面是我的实现,但它正在运行线程,然后将输出发送到 UI,这不是我喜欢的.如何在后台运行此线程?
I am creating a flask application, for one request I need to run some long running job which is not required to wait on the UI. I will create a thread and send a message to UI. The thread will calculate and update the database. But, UI will see a message upon submit. Below is my implementation, but it is running the thread and then sending the output to UI which is not I prefer. How can I run this thread in the background?
@app.route('/someJob')
def index():
t1 = threading.Thread(target=long_running_job)
t1.start()
return 'Scheduled a job'
def long_running_job
#some long running processing here
如何让线程 t1 运行后台并立即发送消息作为回报?
How can I make thread t1 to run the background and immediately send message in return?
推荐答案
最好的办法是使用消息代理.python 世界中有一些优秀的软件就是用来做这个的:
The best thing to do for stuff like this is use a message broker. There is some excellent software in the python world meant for doing just this:
两者都是不错的选择.
以您的方式生成线程几乎从来都不是一个好主意,因为这可能会导致处理传入请求等问题.
It's almost never a good idea to spawn a thread the way you're doing it, as this can cause issues processing incoming requests, among other things.
如果您查看 celery 或 RQ 入门指南,它们会引导您以正确的方式完成此操作!
If you take a look at the celery or RQ getting started guides, they'll walk you through doing this the proper way!
这篇关于带有后台线程的烧瓶应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!