三、在django中使用celery

1、在dango的setting.py所在的目录下新建celery.py文件:

from __future__ import absolute_import, unicode_literals	#避免celery模块与库冲突
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
#避免您始终将设置模块传递给celery程序,必须始终在创建应用程序之前。
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.
#从django的settings模块添加配置源,大写的namespace,指定其他的配置项也必须大写,可以不用该参数
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
#celery自动寻找其他tasks
app.autodiscover_tasks()

#转储其自己的请求信息的任务
@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

2、在setting.py所在的目录下的__init__.py模块中导入次应用程序(确保django启动时加载应用
程序 ),

以便@shared_task将使用这个app:
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',)

3、该@shared_task装饰可以让你无需任何具体的应用程序实例创建任务:

#在tasks.py中
from __future__ import absolute_import, unicode_literals
from celery import shared_task


@shared_task
def add(x, y):
    return x + y
  

4、django ORM cache作为结果后端。


http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django

5、django -A poj worker -l info #poj是定义了celery.py的app。

你可能感兴趣的:(celery)