python wraps.who can give a example
from functools import wraps
def a():
a='aa'
def b开发者_如何转开发():
b="bbb"
c=wraps(a)(b)
print c#what happen?
What is the wraps mean, example is the best.
Quoted from the documentation:
functools.wraps(wrapped[, assigned][, updated])
This is a convenience function for invoking partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)
as a function decorator when defining a wrapper function. For example:
>>> from functools import wraps
>>> def my_decorator(f):
... @wraps(f)
... def wrapper(*args, **kwds):
... print 'Calling decorated function'
... return f(*args, **kwds)
... return wrapper
...
>>> @my_decorator
... def example():
... """Docstring"""
... print 'Called example function'
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
Without the use of this decorator factory, the name of the example function would have been 'wrapper', and the docstring of the original example() would have been lost.
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
@app.route("/")
@login_required
def index():
return "TODO"
Here we can see that the function login_required
becomes a new decorator. The behavior of enter in the router /
is that every person must be login-in
精彩评论