celery 是一个用于实现异步任务的库, 在不少项目中都使用它, 它和 django 融合使用很完美. 使用 celery 能够在实现 http request请求返回 view 前作一些咱们想作的并且耗时的事情而不会让用户等待过久python
django 版本 == 1.11.6django
celery 版本 == 3.1.25app
pip install django-celery
pip install celery
首先须要将 celery 添加到 django 项目的 settings 里, celery 任务和 django 须要一个 中间人(broker),,这里使用的是 django 自带的 broker, 但在生产中通常使用 rabbitmq, Redis 等,在 INSTALLED_APP 中须要添加 djcelery 和 kombu.transport.django, 还有 app 应用。异步
- project/project/ settings.py:函数
import djcelery djcelery.setup_loader() BROKER_URL = 'django://' INSTALLED_APP = ( ... 'app' 'djcelery', 'kombu.transport.django', )
新建 celery.py 建立一个 celery 应用,并添加如下内容this
- project/project/ celery.py:spa
# 相对路径导入, 防止导入 celery 时冲突 from __future__ import absolute_import import os from celery import Celery from django.conf import settings # 让 celery 能找到 django 项目 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') # 建立一个 celery 应用 app = Celery('project') # 导入配置 app.config_from_object('django.conf:settings') # 自动发现 task app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
- project/project/ __init__.py:debug
from __future__ import absolute_import # 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
在 django app 中添加任务,文件名必须是 tasks.py, 在普通 python 函数前加一个 @task() 装饰器就变成了 celery taskcode
- project/app/ tasks.py:orm
from celery.task import task from time import sleep @task() def helloWorld(): print 'helloWorld' sleep(10) print 'helloWorld' return 'helloCelery'
这样,一个任务就建立成功了,只剩下在 view 中调用了
- project/app view.py:
from tasks.py import helloWorld def home(): helloWorld.delay() return HttpResponse('helloCelery')
python manage.py migrate