我复制了django装饰器的代码,并根据我的目的更改了
def valid_token_required(function=None):
def _dec(view_func):
def _view(request, *args, **kwargs):
if 'token' in request.session:
try:
conn = server.GetTokenCon(request.session['token'])
if conn.get_api_status().status == 'good':
kwargs['Connection'] = conn
return view_func(request, *args, **kwargs)
except RateLimitExceededException as e:
return HttpResponseForbidden('token_limit')
except BadCredentialsException as e:
return HttpResponseForbidden('badkey')
return HttpResponseForbidden('require_token')
_view.__name__ = view_func.__name__
_view.__dict__ = view_func.__dict__
_view.__doc__ = view_func.__doc__
return _view
if function is None:
return _dec
else:
return _dec(function)
一切都还可以,但是我无法理解这一行的意义,我试图删除它们并且代码继续工作。有人可以解释一下这条线的含义吗?
_view.__name__ = view_func.__name__
_view.__dict__ = view_func.__dict__
_view.__doc__ = view_func.__doc__
答案 0 :(得分:1)
它更改了最里面的函数(_view
),因此它看起来与它包装的函数具有相同的名称,属性和文档。这有助于在Python解释器中使用help()
,并使堆栈跟踪更清晰。
(注意:同样的事情基本上由stdlib中包含的functools.wraps
装饰器完成。)