烧瓶应用程序与后台线程 [英] flask application with background threads
问题描述
我正在创建一个应用程序,一个请求我需要运行一些长时间运行的作业,而不需要在UI上等待。我将创建一个线程并发送消息给用户界面。线程将计算并更新数据库。但是,UI会在提交时看到消息。
下面是我的实现,但它正在运行线程,然后发送输出到UI,这是我不喜欢。如何在后台运行这个线程?
@ app.route('/ someJob')
def index ():
t1 = threading.Thread(target = long_running_job)
t1.start()
return'计划作业'
def long_running_job
#some长时间运行在这里
如何让线程t1运行后台并立即发送消息返回?
最好的办法就是使用消息代理。在Python世界中有一些优秀的软件可以做到这一点:
按照你的方式产生一个线程几乎不是一个好主意,因为这会导致处理传入请求的问题,其他的东西。
如果你看一下芹菜或RQ入门指南,他们会引导你正确地做这件事!
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
How can I make thread t1 to run the background and immediately send message in return?
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:
- Celery (http://www.celeryproject.org/), and
- RQ (http://python-rq.org/).
Both are excellent choices.
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.
If you take a look at the celery or RQ getting started guides, they'll walk you through doing this the proper way!
这篇关于烧瓶应用程序与后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!