有烧瓶的背景工作者 [英] Background Worker with Flask

查看:164
本文介绍了有烧瓶的背景工作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于python / Flask构建的web应用程序,它有一个连续运行的相应后台作业,定期轮询每个注册用户的数据。



我希望这个后台作业能够在系统启动时保持运行,直到它关闭。而不是设置/etc/rc.d脚本,我只是应用程序启动时,应用程序产生一个新的进程(使用多处理模块)。

因此,使用这个设置,我只需要部署Flask应用程序,这样也可以让后台工作者运行。

这有什么缺点?这是一个完全彻底的破解,在某种方式是脆弱的,或者一个很好的方式来建立一个Web应用程序与相应的后台任务?

尝试烧瓶芹菜。这是一个运行延迟,后台或分布式任务的框架。它需要一个经纪人应用程序:通常使用RabbitMQ,但是您可以使用您已有的数据库,请参阅 Celery项目文档。 p>

使用它就像这样简单:从芹菜中创建工人模块

pre $ .tasks导入任务

@task
def add(x,y):
return x + y

 #celeryconfig.py 
#(for RabbitMQ)
CELERY_RESULT_BACKEND =amqp
CELERY_IMPORTS =(tasks,)



<运行后台进程:

$ p $ code $ celeryd -l info -I任务,处理程序



调用延迟方法:

 > >> from tasks import add 
>>> add.delay(4,4)

< AsyncResult:889143a6-39a2-4e52-837b-d80d33efb22d>

进一步阅读教程

I have a webapp that's built on python/Flask and it has a corresponding background job that runs continuously, periodically polling for data for each registered user.

I would like this background job to start when the system starts and keep running til it shuts down. Instead of setting up /etc/rc.d scripts, I just had the flask app spawn a new process (using the multiprocessing module) when the app starts up.

So with this setup, I only have to deploy the Flask app and that will get the background worker running as well.

What are the downsides of this? Is this a complete and utter hack that is fragile in some way or a nice way to set up a webapp with corresponding background task?

解决方案

Try flask-celery. It's a framework for running delayed, background or distributed tasks. It needs a broker app though: usually RabbitMQ is used, but you can use a database that you already have, see the Celery project docs.

Using it is as simple as this: create workers module

from celery.tasks import task

@task
def add(x, y):
    return x + y

Configure:

# celeryconfig.py
# (for RabbitMQ)
CELERY_RESULT_BACKEND = "amqp"
CELERY_IMPORTS = ("tasks", )

Run the background process:

$ celeryd -l info -I tasks,handlers

Call delayed methods:

>>> from tasks import add
>>> add.delay(4, 4)

<AsyncResult: 889143a6-39a2-4e52-837b-d80d33efb22d>

(read the tutorial further)

这篇关于有烧瓶的背景工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆