简体   繁体   English

无法从 Django 应用程序调用 Celery 任务(缺少位置参数)

[英]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.好吧,我已经翻遍了所有 SO 帖子、Celery 文档等……但我就是想不通。 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.无论我尝试什么或如何尝试从 Django 应用程序调用任务,Celery 都在抱怨我没有提供所需的参数。

"TypeError: add() missing 2 required positional arguments: 'x' and 'y'". “类型错误:add() 缺少 2 个必需的位置参数:'x' 和 '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.我也试过add.delay(x=1, y=2) , celery.send_task("add", [1, 2])和各种各样的其他方式我见过在各种帖子中调用的任务,没有他们工作。

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?我还能缺少什么?

First of all you should add more information on your post related with your Django & Celery Configuration.首先,您应该在与 Django 和 Celery 配置相关的帖子中添加更多信息。

But I think that your mistake is on the @task decorator, because it seems that you'd need to use the Bound tasks :但我认为您的错误在于 @task 装饰器,因为您似乎需要使用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.任务被绑定意味着任务的第一个参数将始终是任务实例(self),就像 Python 绑定方法一样。 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).请注意,任务装饰器的绑定参数将提供对 self(任务类型实例)的访问。

Finally I recommend to you review again the Celery setup on Django .最后,我建议您再次查看 Django 上Celery 设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM