Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from django celery tasks

# 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>

Instead of 7 appearing on home.html I get giberish that looks like this:313e-44fb-818a-f2b2d824a46b. What can I do to get the data from my tasks.py file?

like image 241
PiccolMan Avatar asked Aug 25 '15 23:08

PiccolMan


1 Answers

Simply change:

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

    }

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

to:

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

    }

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

This will be processed by Celery too.

Ading .delay() You setting task as asynchronous and You receiving task_id.

More info in doc: Calling Tasks

like image 67
WBAR Avatar answered Nov 12 '22 01:11

WBAR