django celery redis

django 2.1
python 3.7
os windows10
新版4.x的celery不需要再安装额外的插件,可以直接支持django使用

pip install celery==4.2.0
pip install redis
# windows 如何运行celery4.X版本就需要安装eventlet 不然会报错
pip install eventlet 

说下项目目录结构
django celery redis

新建一个celery.py的文件

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
# 改成你的设置目录,我这里用的是远程连接celery的方式
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
redis_url = 'redis://:[email protected]:6379/0'
app = Celery('mysite', broker=redis_url, backend=redis_url)

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

在__init__.py文件下加入

from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)

在app目录下创建tasks.py存放要执行的异步任务(不能修改tasks名字)

from celery import shared_task
import time


@shared_task
def test_add(x, y):
    time.sleep(5)
    print('执行完毕')
    return x + y

执行celery开始工作

# 这里加上-P eventlet是因为蛋疼的windows环境需要安装eventlet,发布到生成环境的时候就不用安装eventlet

celery  -A mysite worker -l info -P eventlet

启动成功后如图
django celery redis
然后可以在你的views.py里调用tasks的任务

django celery redis
代码执行的时候就不会阻塞,直接返回response,用户体验会得到大幅提升