三、在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。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章