Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Celery task cannot be called (missing positional arguments) from Django app

Ok I've poured over all the SO posts, Celery docs, etc...and I just cannot figure this out. No matter what I try or how I try to call a task from a Django app, Celery is complaining that I'm not supplying the required parameters.

"TypeError: add() missing 2 required positional arguments: 'x' and 'y'".

I'm following a very simple example from their docs...simply using delay, such as:

add.delay(1, 2)

and still the same error. I've also tried add.delay(x=1, y=2), celery.send_task("add", [1, 2]) and a wide variety of other ways I've seen tasks called in various posts and none of them work.

The method is very simple:

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

I've also tried it named, such as:

@task(name="my_add")
def add(x, y):
    return x + y

Same results. What else can I possibly be missing?

like image 843
David White Avatar asked Feb 27 '19 23:02

David White


1 Answers

First of all you should add more information on your post related with your Django & Celery Configuration.

But I think that your mistake is on the @task decorator, because it seems that you'd need to use the Bound tasks:

  • A task being bound means the first argument to the task will always be the task instance (self), just like Python bound methods. Reference.
  • For the other hand, the bind argument means that the function will be a “bound method” so that you can access attributes and methods on the task type instance. Reference

So your code should looks like:

import celery

@task(bind=True, name="my_add")
def add(self, x, y):
    return x + y

Notice that the bind argument to the task decorator will give access to self (the task type instance).

Finally I recommend to you review again the Celery setup on Django.

like image 181
R. García Avatar answered Sep 26 '22 21:09

R. García