如何在装饰函数完成后运行Python装饰器?

Hug*_*own 30 python decorator python-decorators

我想使用装饰器来处理各种函数的审计(主要是Django视图函数,但不是唯一的).为了做到这一点,我希望能够审计执行后的函数- 即函数正常运行,如果它返回没有异常,那么装饰器记录事实.

就像是:

@audit_action(action='did something')
def do_something(*args, **kwargs):
    if args[0] == 'foo':
        return 'bar'
    else:
        return 'baz'
Run Code Online (Sandbox Code Playgroud)

audit_action该功能完成后,将只运行.

Mar*_*ers 39

装饰器通常返回包装函数; 在调用包装函数后,只需将逻辑放在包装函数中.

def audit_action(action):
    def decorator_func(func):
        def wrapper_func(*args, **kwargs):
            # Invoke the wrapped function first
            retval = func(*args, **kwargs)
            # Now do something here with retval and/or action
            print('In wrapper_func, handling action {!r} after wrapped function returned {!r}'.format(action, retval))
            return retval
        return wrapper_func
    return decorator_func
Run Code Online (Sandbox Code Playgroud)

所以audit_action(action='did something')是一个装饰工厂,返回一个范围的decorator_func,这是用来装饰你的do_something(do_something = decorator_func(do_something)).

装修后,您的do_something参考已被替换为wrapper_func.调用wrapper_func()会导致调用原始函数do_something(),然后包装器函数中的代码可以执行操作.

上面的代码与您的示例函数相结合,提供以下输出:

>>> do_something('foo')
In wrapper_func, handling action 'did something' after wrapped function returned 'bar'
'bar'
Run Code Online (Sandbox Code Playgroud)

  • 你不知道有多少不同的装饰器,包装器,func和retvals的组合,我试图让它工作.不仅要感谢代码,还要感谢解释. (2认同)

ava*_*sal 5

您的装饰师可以自己在这里处理它,就像

def audit_action(function_to_decorate):
    def wrapper(*args, **kw):
        # Calling your function
        output = function_to_decorate(*args, **kw)
        # Below this line you can do post processing
        print "In Post Processing...."
        return output
    return wrapper
Run Code Online (Sandbox Code Playgroud)