具有多个装饰器的芹菜任务无法自动注册任务名称 [英] Celery task with multiple decorators not auto registering task name

查看:47
本文介绍了具有多个装饰器的芹菜任务无法自动注册任务名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行如下任务

from mybasetask_module import MyBaseTask

@task(base=MyBaseTask)
@my_custom_decorator 
def my_task(*args, **kwargs):
    pass

我的基本任务如下:

from celery import task, Task

class MyBaseTask(Task):
    abstract = True
    default_retry_delay = 10 
    max_retries = 3 
    acks_late = True

我遇到的问题是芹菜工人正在使用名称注册任务

The problem I'm running into is that the celery worker is registering the task with the name

'mybasetask_module.__inner'

任务已注册当我从任务中删除@my_custom_decorator或为此类任务提供明确的名称时,罚款(这是软件包+模块+功能)

The task is registerd fine (which is the package+module+function) when I remove @my_custom_decorator from the task or if I provide an explicit name to the task like this

from mybasetask_module import MyBaseTask

@task(base=MyBaseTask, name='an_explicit_task_name')
@my_custom_decorator 
def my_task(*args, **kwargs):
    pass

这是预期的行为吗?当我有多个装饰器但没有明确的任务名称时,是否需要做一些事情以使我的任务以默认的自动注册名称进行注册?

Is this behavior expected? Do I need to do something so that my tasks are registered with the default auto registered name in the first case when I have multiple decorators but no explicit task name?

谢谢

推荐答案

使用 functools.wraps()装饰器确保 my_custom_decorator 返回的包装器具有正确的名称:

Use the functools.wraps() decorator to ensure that the wrapper returned by my_custom_decorator has the correct name:

from functools import wraps

def my_custom_decorator(func):
    @wraps(func)
    def __inner():
        return func()
    return __inner

任务名称取自 task 装饰器包装,但是通过在两者之间插入装饰器,您将 __ inner 包装函数赋予了 task functools.wraps()装饰器将所有必要的元数据从 func 复制到包装器中,从而使 task()可以选择正确的名称。

The task name is taken from the function call that the task decorator wraps, but by inserting a decorator in between, you gave task your __inner wrapping function instead. The functools.wraps() decorator copies all the necessary metadata over from func to the wrapper so that task() can pick up the proper name.

这篇关于具有多个装饰器的芹菜任务无法自动注册任务名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆