user1592380
user1592380

Reputation: 36205

Basic celery task function call from inside a django function

I have a django project on an ubuntu EC2 node, that performs a computationally intensive long running process, that typically takes over 60 seconds. I need to cache the results. I've been reading http://www.caktusgroup.com/blog/2014/06/23/scheduling-tasks-celery/ and http://michal.karzynski.pl/blog/2014/05/18/setting-up-an-asynchronous-task-queue-for-django-using-celery-redis/ along with the docs. I've been able to get a basic task working at the command line, but I am unclear on how to start a task from inside a django function.

Right now the structure of my code in my django view is :

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from __future__ import absolute_import
from celery import shared_task

@csrf_exempt
def index(request):

    token = str(request.POST.get('token', False))
    calculator(token)
    return HttpResponse(token)

@shared_task
def calculator(token):

    # do calculation
    # store result in cache

    return

is it as simple as calling:

calculator(token)

in the index function?

Upvotes: 1

Views: 3021

Answers (1)

Seb D.
Seb D.

Reputation: 5195

Almost as simple as you said:

calculator.apply_async()

OR

calculator.delay()

See the docs on how to call tasks for more details.

Upvotes: 2

Related Questions