Don't "s()" and "si()" work properly in Django?

887 views Asked by At

I have add() task in tasks.py in Django as shown below. *I use Celery 5.2.7 and django-celery-results in Django on Windows 11:

# "store/tasks.py"

from celery import shared_task

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

Then, I called add.delay(3, 4) in test() in views.py as shown below:

# "store/views.py"

from .tasks import add
from django.http import HttpResponse

def test(request):

    add.delay(3, 4) # Here

    return HttpResponse("Test")

Then, I could properly get the result below:

Task store.tasks.add[...] succeeded in 0.06s: 7 # Here

But, when calling add.s(3, 4) and add.si(3, 4) in test() as shown below, nothing were displayed:

# "store/views.py"

from .tasks import add
from django.http import HttpResponse

def test(request):

    add.s(3, 4) # Here
    add.si(3, 4) # Here

    return HttpResponse("Test")

So, don't s() and si() work properly in Django?

1

There are 1 answers

1
willeM_ Van Onsem On

The .s(…) method [celery-doc] creates a signature: it is basically an object with data to specify what function to call, and with which parameters. It however does not schedule the task, nor does it evaluate it in the method itself.

As for the .si() [celery-doc] also creates a signature, but an immutable one.

You can schedule the tasks, for example with:

from django.http import HttpResponse

from .tasks import add


def test(request):

    add.s(3, 4).apply_async()
    add.si(3, 4).apply_async()

    return HttpResponse('Test')

This will however not return the result, it will return a task. You can wait for these tasks to return, or for example save the task handler in the database.

It will thus add the task to the queue, and eventually a worker will pick it up and evaluate it.