Python Django2.0集成Celery4.1教程

yipeiwu_com6年前Python基础

环境准备

Python3.6

pip install Django==2.0.1

pip install celery==4.1.0

pip install eventlet (加入协程支持)

安装erlang和rabbitMQ-server

配置settings.py文件

在settings.py文件中添加如下内容

...
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False

CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672'

在settings.py同级目录创建celery.py

celery.py

注意替换: project_name

# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# 设置环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings')

# 注册Celery的APP
app = Celery('project_name')
# 绑定配置文件
app.config_from_object('django.conf:settings', namespace='CELERY')

# 自动发现各个app下的tasks.py文件
app.autodiscover_tasks()

修改settings.py同级目录的init.py文件

from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app

__all__ = ['celery_app']

在某个APP中创建tasks.py文件

tasks.py

# -*- coding: utf-8 -*-

from celery.task import task

# 自定义要执行的task任务
@task
def print_hello():
  return 'hello celery and django...'

配置周期性任务或定时任务

再次编辑settings.py文件,添加如下内容

定时任务的配置格式参考:http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html

from celery.schedules import crontab
CELERY_BEAT_SCHEDULE = {
  # 周期性任务
  'task-one': {
    'task': 'app.tasks.print_hello',
    'schedule': 5.0, # 每5秒执行一次
    # 'args': ()
  },
  # 定时任务
  'task-two': {
    'task': 'app.tasks.print_hello',
    'schedule': crontab(minute=0, hour='*/3,10-19'),
    # 'args': ()
  }
}

启动worker和定时任务

启动worker (切换到manage.py同级目录下执行)

celery -A project_name worker -l info -P eventlet

启动定时任务或周期性任务

celery -A project_name beat -l info

这里备注一下:最好使用supervisord来管理上面这2条命令

存放任务结果的扩展

pip install django-celery-results
Install APP
INSTALLED_APPS = (
  ...,
  'django_celery_results',
)

生成数据库表:python manage.py migrate django_celery_results

配置settings:CELERY_RESULT_BACKEND = 'django-db' (用数据库存放任务执行结果信息)

以上这篇Python Django2.0集成Celery4.1教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python图书管理系统

本文实例为大家分享了python图书管理系统的具体代码,供大家参考,具体内容如下 实现语言:python 图形框架:DTK+2.0 数据库框架:SQLite 3.0 本程序需要以下部件运...

python中学习K-Means和图片压缩

python中学习K-Means和图片压缩

大家在学习python中,经常会使用到K-Means和图片压缩的,我们在此给大家分享一下K-Means和图片压缩的方法和原理,喜欢的朋友收藏一下吧。 通俗的介绍这种压缩方式,就是将原来...

python使用matplotlib库生成随机漫步图

python使用matplotlib库生成随机漫步图

本教程使用python来生成随机漫步数据,再使用matplotlib将数据呈现出来 开发环境 操作系统: Windows10 IDE: Pycharm 2017.1.3 Python...

使用豆瓣提供的国内pypi源 原创

pip使用过程中的痛苦,大家相必都已经知道了,目前豆瓣提供了国内的pypi源,源包相对会略有延迟,但不影响基本使用。 pip install some-package -i https:...

在python中对变量判断是否为None的三种方法总结

三种主要的写法有: 第一种:if X is None; 第二种:if not X; 当X为None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组(...