闭包和装饰器的用处在我另一篇文章有简单的介绍。这里需要有闭包和装饰器的知识
@wraps(view_func)的作用: 不改变使用装饰器原有函数的部分属性(如__name__, doc)
不使用wraps可能出现的ERROR: view_func…endpoint…map…
下面是源码中要保留的原函数属性
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__', '__annotations__')
WRAPPER_UPDATES = ('__dict__',)
下面我们定义了一个装饰器函数,来限制函数的入口权限,和装饰器的使用
def permission_required(permission_name):#闭包第一层,用来获取装饰器传入的变量"permission_name"
def decorator(func):#闭包第二层,用来获取被装饰函数
@wraps(func)#这里面又是三层闭包来实现保留原函数一些特有属性
def decorated_function(*args, **kwargs):#闭包第三层,用来获取被装饰函数manage传入的变量
if not current_user.can(permission_name): #这里是检查用户是否有该权限
abort(403)
return func(*args, **kwargs)
return decorated_function
return decorator
@permission_required("permission_name")
def manage():
pass
下面是源码内容,其实内容不难,里面中文注释是我加的
#wrapped就是manage函数,wrapper是新函数
def update_wrapper(wrapper,wrapped, assigned = WRAPPER_ASSIGNMENTS,updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
try:
value = getattr(wrapped, attr)
except AttributeError:
pass
else:
setattr(wrapper, attr, value)
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Issue #17482: set __wrapped__ last so we don't inadvertently copy it
# from the wrapped function when updating __dict__
wrapper.__wrapped__ = wrapped
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
# Purely functional, no descriptor behaviour
def partial(func, *args, **keywords):# func 是decorated_function #偏函数
"""New function with partial application of the given arguments
and keywords.
"""
if hasattr(func, 'func'):
args = func.args + args
tmpkw = func.keywords.copy()
tmpkw.update(keywords)
keywords = tmpkw
del tmpkw
func = func.func
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords) #为update_wrapper赋予参数主要传入manage函数和assigned,updated并执行update_wrapper函数。保留原函数manage一些属性和方法更新至wrapper中
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES): #wrapped就是manage函数
"""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)
#注意这里update_wrapper传入的函数应该是decorated_function,因为这是第二层函数,
解释:
这也是个三层闭包,
@wraps(func)相当与执行wraps(func)()—>最终得到的是wraps()–>partial()–>newfunc()==>wrapper这个函数,在函数调用的时候立刻执行decorated_function(*args, **kwargs)–>再执行manage()即下面代码。
在调用manage()的时候:首先执行wrapper()–>dedecorated_function()–>manage()中的内容,所以,由于wrapper()函数中包含了从manage()函数中赋予的特有属性和方法比如wrapper.__\name__的值应该是manage。这就是为什么@wraps(fun)保留了原函数的一些信息。
当然如果在 decorated_function中赋值 decorated_function.__name__=manage也可以做到,但是这样一个个完成显然太繁琐。
此文只是自己的理解,仅作参考