Decorator after@task芹菜中的Decorator

2024-04-20 15:05:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在芹菜@task decorator之后应用一个decorator,比如。

@send_email
@task
def any_function():

   print "inside the function"

我可以按照文档中建议的方式让它工作,即将decorator放在任务decorator之前,但在本例中,我希望访问decorator中的任务实例。

@send_电子邮件必须是一个类装饰器,这是我尝试但没有成功的:

class send_email(object):
    ''' wraps a Task celery class '''
    def __init__(self, obj):

        self.wrapped_obj = obj

        functools.update_wrapper(self, obj)

    def __call__(self, *args, **kwargs):

        print "call"

        return self.wrapped_obj.__call__(*args, **kwargs)

    def run(self, *args, **kwargs):

        print "run"

        return self.wrapped_obj.__call__(*args, **kwargs)

    def __getattr__(self, attr):

        if attr in self.__dict__:

            return getattr(self, attr)

        return getattr(self.wrapped_obj, attr)

我永远无法在调用或运行函数函数中获取print语句以显示在工作进程或调用方中。

我们如何在不依赖于基于类的任务定义的情况下装饰芹菜任务(这样装饰器就在@Task之上,函数定义之上)。

谢谢你的帮助!

米格尔


Tags: 函数selfsendobjreturndefargs装饰
2条回答

任务装饰器不返回类,而是返回实例。

似乎您的问题应该是“如何访问decorator内部的任务”,而不是如何首先应用decorator。

在即将发布的3.1(开发版本)中,您可以使用绑定任务来完成此任务:

def send_email(fun):
    @wraps(fun)
    def outer(self, *args, **kwargs):
        print('decorated and task is {0!r}'.format(self))
        return fun(self, *args, **kwargs)

    return outer

@task(bind=True)
@send_email
def any_function(self):
    print('inside the function')

对于以前的版本,可以使用current_task

from celery import current_task

def send_email(fun):

    @wraps(fun)
    def outer(*args, **kwargs):
        print('decorated and task is: %r' % (current_task, ))
        return fun(*args, **kwargs)


@task
@send_email
def any_function():
    print('inside the function')

“before”在视觉上看起来像“after”。

例如,这个:

@decorator1
@decorator2
@decorator3
def func():
  pass

相当于:

def func():
  pass

func = decorator1(decorator2(decorator3(func)))

这意味着您必须在@task之后写入@send_email,才能在@task之前应用它。例如:

@task
@send_email
def any_function():
    print "inside the function"

相关问题 更多 >