django和celery的安装略
一、创建django项目
假设你的项目目录是这样的
- proj/
- manage.py
- proj/
- __init__.py
- settings.py
- urls.py
二、新建celery.py
文件位置proj/proj/celery.py
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.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
app = Celery('proj')
# 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
文件位置proj/proj/__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
示例代码
# -*- coding:utf8 -*-
from __future__ import absolute_import, unicode_literals
from celery import shared_task
import time
# 这里不再使用@app.task,而是用@shared_task,是指定可以在其他APP中也可以调用这个任务
@shared_task
def add(x, y):
print('########## running add #####################')
return x + y
@shared_task
def minus(x, y):
time.sleep(30)
print('########## running minus #####################')
return x - y
五、在settings.py中增加celery配置
# 简单配置
CELERY_BROKER_URL = "redis://localhost"
CELERY_RESULT_BACKEND = "redis://localhost"
六、启动worker
celery -A DeviceOperations.celery:app worker --loglevel=info
# windows环境下添加 --pool=solo选项
此处需要注意的是需要使用 --app参数,参数用来指定app所在的位置,也就是我们之前在celery.py中定义的
app = Celery('proj')
否则会报错
Error:
Unable to load celery application.
The module do was not found.
附录
redis Windows下载地址