Returning celery task id to view

In my celery task, I want to calculate median of an array.

My view:

import myapp.tasks as tasks

def my_view(request): 
    data_arr = [[1,2], [3,4]]
    response = {
        'median': tasks.median.delay(data_arr).id
    }
    return HttpResponse(json.dumps(response))   

Here's the task file:

from celery import shared_task
import numpy

@shared_task
def median(arr):
    return numpy.mean(arr)

When I call the view, I can get the following output:

{"median": "88edea52-c60a-42a8-ad8d-799a4c7117a6"}

The problem is celery outputs following error:

File "/Users/tolga/Desktop/projects/python/nadir/process/tasks.py", line 7, in median
return numpy.mean(arr).id
AttributeError: 'numpy.float64' object has no attribute 'id'

I understand the error, but I can't figure out how to proceed.

if you want to calculate median of an array to fix this issue you will need to remove the call to .id from your task function and nstead of returning the id of the task result, you can simply return the result of numpy.mean directly:

@shared_task
def median(arr):
    return numpy.mean(arr)

This will return the median value of the arr array as the result of the task.

but if u want to return the task's id as the result of the view, you can use the AsyncResult class to retrieve the task's result and return it in the view:

from celery.result import AsyncResult

def my_view(request): 
    data_arr = [[1,2], [3,4]]
    task = tasks.median.delay(data_arr)
    response = {
        'median': AsyncResult(task.id).result
    }
    return HttpResponse(json.dumps(response))

this is will retrieve the result of the task and include it in the response object rather than the task's id

Back to Top