閉包和裝飾器的用處在我另一篇文章有簡單的介紹。這裏需要有閉包和裝飾器的知識
@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也可以做到,但是這樣一個個完成顯然太繁瑣。
此文只是自己的理解,僅作參考