celery 4.0在django 1.8.x以上的簡單使用

celery 是基于python實現(xiàn)的一個分布式任務(wù)框架。
在celery 3.2.x 以下的版本和celery 4.x 版本涉及到的配置方式以及使用方式有點不同。
文章中的內(nèi)容是介紹celery 4.0 在django中如何配置,以及簡單的運用。
celery 4.x 僅支持django 1.8以上版本。
未來的celery 5.x 以上僅支持python 3.5或者更新的版本。
1:配置應(yīng)用環(huán)境
使用虛擬環(huán)境去配置環(huán)境

mkvirtualenv celery_demo
pip install django==1.8.10
pip install celery==4.0.2
django-admin start startproject celerydemo #創(chuàng)建django項目
cd ./celery_demo 
python manage.py startapp demo #創(chuàng)建django app  

在完成上述的項目創(chuàng)建后,那么需要的是進行一些配置。
對celery.py的配置
/celery_demo/celery_demo/celery.py

# coding:utf-8
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', 'celerydemo.settings')

app = Celery('celerydemo')

# Using a string here means the worker don'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))

搞好celery.py 文件后,需要在/celery_demo/celery_demo/init.py 進行一些配置

# coding:utf-8
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的 task總會被django的引用和支持。


當(dāng)完成上述的步驟后,可以嘗試下執(zhí)行celery 程序

celery worker -A celery_demo -l info

當(dāng)使用上述命令的時候,會看到Error

[2017-01-09 17:31:52,299: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused.
Trying again in 2.00 seconds...

這個時候得在/celery_demo/celery_demo/settings.py 中配置好CELERY_BROKER_URL 的參數(shù)。
我使用的是redis作為broker
配置如下:

#/celery_demo/celery_demo/settings.py
CELERY_BROKER_URL = 'redis://127.0.0.1/2'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'

還需要install redis

pip install redis

這個時候好了,可以執(zhí)行

celery worker -A celerydemo -l info

會顯示celery已經(jīng)在運行了。
那么可以使用下面的去測試代碼或者項目。

python manage.py shell
#在命令行腳本中
from celerydemo.celery import debug_task
debug_task.delay()

會到看終端中出現(xiàn)log

[2017-01-09 17:37:29,279: WARNING/PoolWorker-2] Request: <Context: {u'origin': u'gen78371@youyoudeMacBook-Pro.local', u'args': [], u'chain': None, u'root_id': u'384bb5a3-f041-48e2-a4c6-f19c730f4eb7', u'expires': None, u'is_eager': False, u'correlation_id': u'384bb5a3-f041-48e2-a4c6-f19c730f4eb7', u'chord': None, u'reply_to': u'6254263f-0c98-371e-b58e-3ca94fab880e', u'id': u'384bb5a3-f041-48e2-a4c6-f19c730f4eb7', u'kwargsrepr': u'{}', u'lang': u'py', u'retries': 0, u'task': u'celerydemo.celery.debug_task', u'group': None, u'timelimit': [None, None], u'delivery_info': {u'priority': 0, u'redelivered': None, u'routing_key': u'celery', u'exchange': u''}, u'hostname': u'celery@youyoudeMacBook-Pro.local', 'called_directly': False, u'parent_id': None, u'argsrepr': u'()', u'errbacks': None, u'callbacks': None, u'kwargs': {}, u'eta': None, '_protected': 1}>
[2017-01-09 17:37:29,280: INFO/PoolWorker-2] Task celerydemo.celery.debug_task[384bb5a3-f041-48e2-a4c6-f19c730f4eb7] succeeded in 0.00210009199509s: None

那么大體上celery 4.x 已經(jīng)在django中配置好,甚至可以執(zhí)行部分的異步任務(wù)。


下面的是拓展
1:如何處理定時任務(wù)
a:

pip install django-celery-beat

b: 添加 django_celery_beat 模塊到 項目的settings.py 的INSTALLED_APPS 中

 INSTALLED_APPS = ( ..., 'django_celery_beat', )

c:應(yīng)用模塊中的表單到數(shù)據(jù)庫中

python manage.py migrate

d:使用django 的任務(wù)心跳調(diào)度器

celery beat -A celerydemo -l info

e:配置定時任務(wù)

python manage.py runserver 
# :8080/admin/django_celery_beat/ 中配置

2:定時任務(wù)的返回結(jié)果處理
以往的數(shù)據(jù)中,返回的結(jié)果是可以不需要或者忽略的。
a:配置上面很簡單

pip install django-celery-results

b:添加 django_celery_results 到 INSTALLED_APPS
c:創(chuàng)建應(yīng)用django_celery_results 所需的表單

python manage.py migrate django_celery_results

d:在配置文件中使用 django_celery_results 作為celery的使用

#settings.py
CELERY_RESULT_BACKEND = 'django-db'
or 
CELERY_RESULT_BACKEND = 'django-cache'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容