使用Django时对Celery进行的备忘录


安装

$ pip install django
$ pip install django-celery
$ pip freeze
amqp==1.4.8
anyjson==0.3.3
billiard==3.3.0.22
celery==3.1.19
Django==1.9
django-celery==3.1.17
kombu==3.0.30
pytz==2015.7
wheel==0.24.0

Django的设置

创建项目

$ django-admin.py startproject proj
$ python manage.py startapp sampleapp
/c/dev/projects/proj

确认

|--manage.py
|--proj
| |--__init__.py
| |--settings.py
| |--urls.py
| |--wsgi.py
|--sampleapp
| |--__init__.py
| |--admin.py
| |--apps.py
| |--migrations
| | |--__init__.py
| |--models.py
| |--tests.py
| |--views.py

两个设定

以下是/settings.py文件的释义。

INSTALLED_APPS = (

    'djcelery',
    'kombu.transport.django',
    'sampleapp',
)

# Celery Setting
import djcelery
djcelery.setup_loader()
BROKER_URL = 'django://'
# Tasks will be executed asynchronously.
CELERY_ALWAYS_EAGER = False

/proj/celery.py -> /proj/ 芹菜.py

from __future__ import absolute_import

import os

from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

from django.conf import settings  # noqa

app = Celery('proj')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

app.conf.update(
    CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

/proj/init.py 的翻译选项如下:
/proj/init.py 初始化.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  # noqa

三个任务的执行

/sampleapp/tasks.py 的中文翻译

import time

from celery import task

@task
def add(a, b):
    time.sleep(10)
    return a + b

进行4个数据库的初始化

$  python manage.py makemigrations djcelery
Migrations for 'djcelery':
  0002_auto_20151211_1830.py:
    - Alter field status on taskmeta
    - Alter field state on taskstate

$  python manage.py migrate djcelery
Operations to perform:
  Apply all migrations: djcelery
Running migrations:
  Rendering model states... DONE
  Applying djcelery.0002_auto_20151211_1830... OK

执行

启动Celery工作进程

$ celery -A proj worker -l info -c 1

在Django的shell中执行

$  python manage.py shell
(InteractiveConsole)
>>> from sampleapp.tasks import add
>>> result = add.delay(1, 2)
>>> result.ready()
False
>>> result.ready()  # 10秒経過
True
>>> result.get()
3
bannerAds