如何从 django celery 任务中获取数据

Pic*_*Man 4 python django scheduled-tasks celery

# In tasks.py file
from __future__ import absolute_import

from celery import shared_task

@shared_task
def add(x, y):
    return x + y

# In views.py
def home(request):
    context = {
        'add': tasks.add.delay(5,2)

    }

    return render(request, "home.html", context)

# In home.html
<h1>{{ add }}</h1>
Run Code Online (Sandbox Code Playgroud)

home.html 上出现的不是 7,而是看起来像这样的胡言乱语:313e-44fb-818a-f2b2d824a46b。我该怎么做才能从我的 tasks.py 文件中获取数据?

WBA*_*BAR 5

只需更改:

def home(request):
    context = {
        'add': tasks.add.delay(5,2)

    }

    return render(request, "home.html", context)
Run Code Online (Sandbox Code Playgroud)

到:

def home(request):
    context = {
        'add': tasks.add.delay(5,2).get()

    }

    return render(request, "home.html", context)
Run Code Online (Sandbox Code Playgroud)

这也将由 Celery 处理。

Ading .delay()You 将任务设置为异步并接收task_id.

文档中的更多信息:调用任务