关于芹菜的问题

Questions about Celery

我正在尝试了解 Celery 是什么以及它的作用,我已经学习了一些基础教程,例如 first steps with Celery and this 一个,我有几个关于 Celery 的问题:

在(第一步)教程中,您启动了一个 Celery worker,然后您基本上可以打开一个解释器并调用定义为的任务:

>>> from tasks import add
>>> add.delay(4, 4)

所以我的问题是:

  1. 这里发生了什么? add() 是我们在任务文件中编写的方法,我们正在调用 add.delay(4,4)。所以我们在一个方法之上调用一个方法!?

  2. 这是如何工作的? 'delay' 方法如何添加到 'add'?

  3. Celery worker 做4+4相加的工作吗?与该方法的调用者所做的工作相反? - 就像我刚刚在解释器中定义了一个名为 add 的方法并执行了一样

    添加(4,4)

  4. 如果 3 的答案是肯定的,那么 Celery 如何知道它必须做一些工作?我们所做的就是 - 从我们编写的模块中导入一个方法并调用该方法。控制权如何传递给 Celery worker?

另外,在回答 #4 时,如果你能告诉我你是怎么知道的,那就太好了。我很想知道这些事情是否记录在我 missing/failing 理解的某个地方,以及我如何知道答案。提前致谢!

What's happening here? add() is a method that we wrote in the tasks file and we're calling add.delay(4,4). So we're calling a method over a method!?

在 Python 中一切都是对象。一切都有属性。 Functions/methods也有属性。例如:

def foo(): pass
print(foo.__name__)

这在语法方面没什么特别的。

How does this work? How does the delay method get added to add?

@app.task装饰器就是这样做的。

Does the Celery worker do the work of adding 4+4? As opposed to the work being done by the caller of that method?

是的,工人就是这样做的。否则这将是非常荒谬的。您将两个参数(44)传递给 Celery 系统,Celery 系统将它们传递给工作人员,工作人员完成实际工作,在本例中为加法。

If the answer to 3 is yes, then how does Celery know it has to do some work? All we're doing is - importing a method from the module we wrote and call that method. How does control get passed to the Celery worker?

同样,@app.task 装饰器在这里抽象了很多魔法。这个装饰器将函数注册到 celery worker 池中。它还为允许您 调用 芹菜工作池中的函数的相同方法添加了魔法属性,即 delay。想象一下:

def foo(): pass
celery.register_worker('foo', foo)
celery.call('foo')

装饰器本质上就是这样做的,只是你不必以各种方式重复写foo。它使用函数本身作为您的标识符,纯粹作为语法糖,因此您不必在代码中区分 foo()'foo'