Celery
celery 是一个用于实现异步任务的库, 在很多项目中都使用它, 它和 django 融合使用很完美. 使用 celery 可以在实现 http request 请求返回 view 前做一些我们想做的而且耗时的事情而不会让用户等待太久
环境
django 版本 == 1.11.6
celery 版本 == 3.1.25
安装
- 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 应用, 并添加以下内容
- - project/project/ celery.py:
- # 相对路径导入, 防止导入 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:
- 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 task
- - project/App/ tasks.py:
- 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
来源: https://www.cnblogs.com/peng104/p/10580720.html