【Python】Flask中@wraps的使用

【Python】Flask中@wraps的使用,第1张

【Python】Flask中@wraps的使用

  

  先说总结,白话来讲,@wraps相当于是装饰器的装饰器。


  python内置的方法使用解释,看起很复杂的样子┓( ´∀` )┏

def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)

  

  下面举个栗子:

from functools import wraps

# 用户角色权限确认
def permission_required():
def decorator(f):
#@wraps(f)
def decorated_function():
return 'this is decorated function'
return decorated_function
return decorator # 管理员权限确认
def admin_required(f):
return permission_required()(f) if __name__=='__main__':
def test_func():
return 'this is test function'
print(admin_required(test_func))

  

  不用@wraps时,打印出来是酱婶儿的

<function permission_required.<locals>.decorator.<locals>.decorated_function at 0x00000000030411E0>

  

  使用之后看起来清爽了很多

<function test_func at 0x0000000002FC11E0>

  

  通过对比结果,@wraps的作用猜出来个大概。


  使用之后它返回的是参数test_func方法的地址。


也就是说,如果你想使用参数方法的一些属性,就需要使用@wraps了。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/587121.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存