参考:https://www.cnblogs.com/wdliu/p/9530219.html
https://blog.csdn.net/lineuman/article/details/88988812
https://blog.csdn.net/mythest/article/details/87629364
https://www.django.cn/course/show-21.html
如tutorial project:
E:.
│ db.sqlite3
│ manage.py
│
│
├─snippets
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ serializers.py
│ │ tasks.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│
├─templates
└─tutorial8
│ celery.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
一、在项目配置文件,tutorial8中:
1.添加celery.py
from celery import Celery
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial8.settings')
app = Celery('snippets')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
2. settings.py
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
CELERY_RESULT_SERIALIZER = 'json'
3. __init__.py
from .celery import app as celery_app
__all__ = ['celery_app']
二、应用模块 snippets:
1.添加 tasks.py
from celery import shared_task
@shared_task
def add(x, y):
return x + y
@shared_task
def mul(x, y):
return x*y
2. views.py
from . import tasks
from django.http import JsonResponse
def index(request, *args, **kwargs):
res = tasks.add.delay(1, 3)
print("ready:", res.ready())
if res.ready():
print(res.get())
return JsonResponse({'status': 'successful', 'task_id': res.task_id})
3. urls.py
from django.conf.urls import url
from snippets import views
from django.urls import path, include
urlpatterns = [
url('^index/$', views.index),
url('^snippets/$', views.SnippetList.as_view({'get': 'hello'})),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
]
四、启动顺序:
1. 启动redis-server
2. 先启动 django程序
3. 进入tutorial, 启动内部的tutorial8模块:
celery -A tutorial8 worker -l info -P eventlet
4. 测试api
5. 进入redis-cli
6. 取出计算结果:
(1) get celery-task-meta-'task_id'(task_id无引号)
(2) 进入ipython:
from celery.result import AsyncResult
res = AsyncResult('task_id')
res.result
4.进入