简体   繁体   English

Celery:使用多个参数链接任务

[英]Celery: Chaining tasks with multiple arguments

The celery documentation tells me that if multiple tasks are chained together, the result of the first task will be the first argument of the next. celery文档告诉我,如果多个任务链接在一起,第一个任务的结果将是下一个任务的第一个参数。 My problem is, I can't get it to work when I have a task that returns multiple results. 我的问题是,当我有一个返回多个结果的任务时,我无法让它工作。

Example: 例:

@task()
def get_comments(url):
    #get the comments and the submission and return them as 2 objects
    return comments, submission

@task
def render_template(threadComments, submission):
    #render the objects into a html file
    #does not return anything

Now, if I call them in a chain like (get_comments(url) | render_template()).apply_asnc() python will throw an TypeError: render_template() takes exactly 2 arguments (0 given) . 现在,如果我在链接中调用它们(get_comments(url)| render_template())。apply_asnc()python将抛出一个TypeError: render_template() takes exactly 2 arguments (0 given)

I can see that the results are not unwrapped and applied to the arguments. 我可以看到结果没有打开并应用于参数。 If I only call get_comments, I can do: 如果我只调用get_comments,我可以这样做:

result = get_comments(url)
arg1, arg2 = result

and get both results. 并得到两个结果。

There are two mistakes here. 这里有两个错误。

First, you don't have to call get_comments() and render_template() . 首先,您不必调用get_comments()render_template() Instead, you should use the .s() task method. 相反,您应该使用.s()任务方法。 Like: 喜欢:

( get_comments.s(url) | render_template.s()).apply_async()

In your case, you launch the function first, and then tries to join functions results to a chain. 在您的情况下,首先启动该函数,然后尝试将函数结果连接到链。

Second, actually, you don't return "two results" from your first task. 其次,实际上,你不会从第一个任务中返回“两个结果”。 Instead, you return a tuple, containing both results, and this tuple is passed to the second task as the single object. 相反,您返回一个包含两个结果的元组,并将此元组作为单个对象传递给第二个任务。

Therefore, you should rewrite your second task as 因此,您应该将第二个任务重写为

@task
def render_template(comments_and_submission):
   comments, submission = comments_and_submission

If you fix these, it should work. 如果你修复这些,它应该工作。

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

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