python-celery使用教程

笑着哭i 提交于 2019-11-29 23:51:06

Celery

Celery是Python开发的分布式任务调度模块。分为任务分发,任务队列,worker3个部分。celery的出现,解决了python运行后台任务的需求。

这篇文章介绍的celery版本是3.1.18

celery架构

                                                                +------------------+
                                                       +------> | celery worker.1  |
+-----------------+       +-----------------------+    |        +------------------+
|   web service   +-----> | job queue(redis or ..)+----+                            
+-----------------+       +-----------------------+    |        +------------------+
                                                       +------> | celery worker.2  |
                                                       |        +------------------+
                                                       |                            
                                                       |        +------------------+
                                                       +------> | celery worker.[n]|
                                                                +------------------+

任务队列,支持如redis,RabbitMQ甚至数据库。通常redis是最好的选择,不过数据库在本地使用的时候,也是不错的。

安装celery

使用douban的pypi镜像,安装会快一点。

pip install -i http://pypi.douban.com/simple celery

普通使用

使用Redis作为Broker时,再安装一个celery-with-redis

开始编写tasks.py:

import time
from celery import Celery

celery = Celery('tasks', broker='redis://localhost:6379/0')

@celery.task
def sendmail(mail):
    print('sending mail to %s...' % mail['to'])
    time.sleep(2.0)
    print('mail sent.')

if __name__ == '__main__':
    sendmail.delay(dict(to='myemail@gogs.io'))

启动worker

celery -A tasks worker

运行任务

python tasks.py

这里普通的调用方式是sendmail(...) 如果改成后台运行就变成了sendmail.delay(...)

Celery默认设置就能满足基本要求。Worker以Pool模式启动,默认大小为CPU核心数量,缺省序列化机制是pickle,但可以指定为json。由于Python调用UNIX/Linux程序实在太容易,所以,用Celery作为异步任务框架非常合适。

flask中使用celery

web中使用celery是常有的事情。heroku官方就推荐python程序使用celery。 代码,我放到github上一份https://github.com/codeskyblue/celery-examples

首先创建一个web.py文件

from flask import Flask
from celery import Celery


def make_celery(app):
    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task
    class ContextTask(TaskBase):
        abstract = True
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery

app = Flask(__name__)
app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379',
    CELERY_RESULT_BACKEND='redis://localhost:6379'
)
celery = make_celery(app)

编写任务函数

@celery.task()
def add_together(a, b):
    res = a + b
    print res
    return res

然后是一个主页, 请求主页的时候,就会自动调用add_together这个函数,交给celery运行

@app.route('/')
def homepage():
    a = random.randint(0, 10)
    b = random.randint(0, 10)
    add_together.delay(a, b)
    return 'Create new task {} + {}'.format(a, b)

然后还需要编写一个run.py文件(这里需要分开两个文件)

from web import app

if __name__ == '__main__':
    app.run()

启动web应用python web.py,启动worker的方法celery -A web.celery worker

如果需要用sqlite作为后端的话,也是可以的,首先需要安装pip install sqlalchemy

flask的app配置稍微改下

app.config.update(
    CELERY_BROKER_URL='sqla+sqlite:///queue.db',
    CELERY_RESULT_BACKEND='db+sqlite:///queue.db',
    CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']
)

然后,celery就会用本地的queue.db文件,作为队列了。

Refs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!