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

2024-05-22 03:05:52 发布

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

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

类似于:

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

其中audit_action只在函数完成后运行。


Tags: django函数视图returndef记录argsaction
2条回答

Decorators通常返回包装函数;只需在调用包装函数后将逻辑放入包装函数。

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

所以audit_action(action='did something')是一个decorator工厂,它返回一个作用域decorator_func,用于修饰do_somethingdo_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'

你的装潢师可以自己处理,就像

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

相关问题 更多 >