获取多次修饰的函数的返回值

Getting the returned value of a function that has been decorated multiple times

有没有办法在使用多个装饰器时获取原始函数的返回值? 这是我的装饰器:

def format_print(text):

    def wrapper():
        text_wrap = """
**********************************************************
**********************************************************
        """
        print(text_wrap)
        text()
        print(text_wrap)
    
    return wrapper

def role_required(role):
  
    def access_control(view):
    
        credentials = ['user', 'supervisor']

        def wrapper(*args, **kwargs):
        
            requested_view = view()
            if role in credentials:
                print('access granted')
                return requested_view
            else:
                print('access denied')
                return '/home'

        return wrapper

    return access_control

当我 运行 使用 @role_required 下面的函数时,我得到了我期望的结果:

@role_required('user')
def admin_page():
    print('attempting to access admin page')
    return '/admin_page'
x = admin_page()
print(x)

Returns:

attempting to access admin page
access granted
/admin_page

但是当我取消注释第二个装饰器时,admin_page() returns None

**********************************************************
**********************************************************

attempting to access admin page
access granted

**********************************************************
**********************************************************

None

有人可以告诉我哪里出错了,以及如何从具有多个装饰器的函数中获取返回值。

非常感谢

这是因为您确实需要这样做:

def format_print(text):

    def wrapper():
        text_wrap = """
**********************************************************
**********************************************************
        """
        print(text_wrap)
        result = text()
        print(text_wrap)
        return result
    
    return wrapper

否则您的包装器将始终 return None.