当使用多个decorator时,是否有方法获取原始函数的返回值? 以下是我的装饰师:
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)
返回:
attempting to access admin page
access granted
/admin_page
但是当我取消注释第二个decorator时,admin_page()返回None
**********************************************************
**********************************************************
attempting to access admin page
access granted
**********************************************************
**********************************************************
None
有人能告诉我哪里出了问题,以及如何从具有多个decorator的函数中获取返回值
非常感谢
这是因为您实际上需要这样做:
否则,包装器将始终返回
None
相关问题 更多 >
编程相关推荐