python - understanding functools.wraps -
i using flask-restful , trying have rest endpoints using technique showed here
the main code is
def authenticate(func): @wraps(func) def wrapper(*args, **kwargs): if not getattr(func, 'authenticated', true): return func(*args, **kwargs) acct = basic_authentication() # custom account lookup function if acct: return func(*args, **kwargs) restful.abort(401) return wrapper class resource(restful.resource): method_decorators = [authenticate] # applies inherited resources i same way , seems work, not sure happens @wraps?
seems magic me @ moment , did not understand following
a.) seems function wrapped @wraps passed wrapper, wrapper returning?
possible answer: passed function initially?
if yes, how can pass more information acct object function receives account object , don't have database fetch it?
update based on example, rest endpoint looks
class userresource(restresource): def get(self, uuid): return {'method': 'get user -> ' + uuid} and call like
curl -x http://127.0.0.1:5000/users/validuuid now when every request authenticated, see if valid acct object exists , if exists, delegate control endpoint
question:
since making 1 database call find out acct object, possible pass in endpoint when valid acct located?
this way 2 things happen
a.) know call authenticated
b.) reuse acct object can use further work, rather making db call again , acct object validuuid again
how can achieve ?
authenticate decorator -- takes function , returns modified version of function (which implemented wrapping function , wrapping it).
now, problem wrappers don't act original function in ways -- may missing docstrings, have wrong __name__ (wrapper instead of should called), , other blemishes. might important if other code using information. functools.wraps simple function adds information original function (here, func) wrapper function, behaves more original function. (technically, decorator, confusing part, don't have worry detail. know nice tool copies attributes wrapped function wrapper function).
thus, when write
new_function = authenticate(old_function) or more commonly
@authenticate def function(...) new_function more old_function.
Comments
Post a Comment