django-celeryのインストール

以下、2012/12/02に全面的に追記/改修した。

概要

django-celeryのインストール手順と、簡単な動作確認の方法について以下記載する。

django-celeryとは

celeryを使う(CentOS)で書いた"celery"をdjangoと連携して動作させるモジュールである。
これを使うことで,djangoの設定ファイル(settings.py)内の"INSTALLED_APPS"に記載したアプリ向けモジュールを、celeryのタスクとして利用し、djangoからceleryタスク実行できる。
以下は、公式サイトの説明。

django-celery provides Celery integration for Django;
Using the Django ORM and cache backend for storing results,
autodiscovery of task modules for applications listed in INSTALLED_APPS, and more.

インストール手順

easy_install django-celeryのみで基本OK。
ただし、自分の場合、途中で以下のようなエラーが出た。
(けど結果的にはインストールされていた。正しくインストールされていないかもしれないが...)

$ sudo easy_install django-celery
(中略)
Installed /usr/lib/python2.6/site-packages/billiard-2.7.3.18-py2.6-linux-x86_64.egg
Finished processing dependencies for django-celery
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib/python2.6/site-packages/billiard-2.7.3.10-py2.6-linux-x86_64.egg/billiard/util.py", line 291, in _exit_function
    for p in active_children():
  File "/usr/lib/python2.6/site-packages/billiard-2.7.3.10-py2.6-linux-x86_64.egg/billiard/process.py", line 75, in active_children
    _cleanup()
TypeError: 'NoneType' object is not callable
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib64/python2.6/multiprocessing/util.py", line 258, in _exit_function
    info('process shutting down')
TypeError: 'NoneType' object is not callable
Error in sys.exitfunc:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib64/python2.6/multiprocessing/util.py", line 258, in _exit_function
    info('process shutting down')
TypeError: 'NoneType' object is not callable

なお、Install途中で、勝手に(親切に) celeryのVersionがupgradeされていたようであった。
(3.0.1->3.0.12になった)

インストールの確認

上記でうまく言ってなさそうだったので、sudoでなくsu -になってやってみたが、入っている様子であった。

# easy_install django-celery
Searching for django-celery
Best match: django-celery 3.0.11
Processing django_celery-3.0.11-py2.6.egg
django-celery 3.0.11 is already the active version in easy-install.pth
Installing djcelerymon script to /usr/bin
Installing djcelerymon script to /usr/bin

Using /usr/lib/python2.6/site-packages/django_celery-3.0.11-py2.6.egg
Processing dependencies for django-celery
Finished processing dependencies for django-celery

一応、VERSIONの確認。
python:2.6.6
djcelery:3.0.11
celery:3.0.12
django:1.4.0

root@localhost:~# python
Python 2.6.6 (r266:84292, Sep 11 2012, 08:34:23) 
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import djcelery
>>> djcelery.VERSION
(3, 0, 11)
>>> import celery
>>> celery.VERSION
(3, 0, 12)
>>> import django
>>> django.VERSION
(1, 4, 0, 'final', 0)
>>> 

動作確認

django側の設定を行い、続いてサンプルタスクを用意して、実行する例を以下に記載する。
djangoプロジェクトの作成。(ここでは"mysite"とした。)

$ django-admin.py startproject mysite
$ cd mysite/

できたdjangoの設定ファイル(setting.py)に以下を記載する。

setting.pyの設定

冒頭に、モジュールロードのための設定を追記する。

import djcelery
djcelery.setup_loader()

djceleryモジュールをdjangoから呼べるように設定を追記する。

INSTALLED_APPS += ("djcelery", )

メッセージブローカー*1のURL指定を行う。
(RabbitMQを利用する場合は以下で動いた)

BROKER_URL = 'amqp://guest:guest@localhost:5672/'

DBの設定を追記する。
(以下は簡単のためにsqliteを利用する設定例)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.                 
        'NAME': 'sample_django_celery',                      # Or path to database file if using sqlite3.                    
        'USER': '',                      # Not used with sqlite3.                                                            
        'PASSWORD': '',                  # Not used with sqlite3.                                                            
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.                         
	'PORT': '',                      # Set to empty string for default. Not used with sqlite3.                           
    }
}

DBの初期化

$ python ./manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table celery_taskmeta
Creating table celery_tasksetmeta
Creating table djcelery_intervalschedule
Creating table djcelery_crontabschedule
Creating table djcelery_periodictasks
Creating table djcelery_periodictask
Creating table djcelery_workerstate
Creating table djcelery_taskstate

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes  ★この辺適当に答える
Username (leave blank to use 'username'):   ★この辺適当に答える
E-mail address: username@hoge.com   ★この辺適当に答える
Password:   ★この辺適当に答える
Password (again):   ★この辺適当に答える
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

※ここで、参考サイトのとおりに、"migrate"しようとしたら以下のように実行できなかったのでスルーした。

$ python ./manage.py migrate djcelery
Unknown command: 'migrate'
Type 'manage.py help' for usage.

アプリ初期化

$ python manage.py startapp celerytest

First steps with Djangoに従って、サンプルアプリとしてcelerytestにtasks.pyをつくる。
具体的には以下の通り。
celerytest/tasks.pyに以下を記載する。

from celery import task
@task()
def add(x, y):
    return x + y

celerytestのtasksモジュールをdjangoから呼べるように設定を追記する。

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:                                                                    
    # 'django.contrib.admin',                                                                                         
    # Uncomment the next line to enable admin documentation:                                                          
    # 'django.contrib.admindocs',                                                                                     
    'djcelery', # for django 2012/11/11added                                                                
    'celerytest.tasks', ★ここ
)

※記載の仕方は、project.appのように指定する。

django+celeryの起動。

$ python ./manage.py celery worker --loglevel=debug

command promptからadd(3,5)を実行。

$ python
Python 2.6.6 (r266:84292, Sep 11 2012, 08:34:23) 
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from celerytest.tasks import add
>>> add.delay(3,5)
<AsyncResult: 24ea2b65-2898-4756-bc00-9bee2314cbcc>
>>>

この時、django+celeryを起動した側のlogを見ると、以下のように、3+5の結果の"8"を表示していることがわかる。

[2012-12-01 23:51:47,143: INFO/MainProcess] Task celerytest.tasks.add[24ea2b65-2898-4756-bc00-9bee2314cbcc] succeeded in 0.045814037323s: 8

celerydaemon化などは、以前やって少々面倒くさかったのでいつか記載するかも。

*1:celeryを使う(CentOS)あたりも参照。