django+celery

2 篇文章 0 订阅
2 篇文章 0 订阅

参考: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.进入

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值