在编写一些视图来响应ajax请求时,我发现有点奇怪的是,login_required装饰器总是为未经过身份验证的用户返回302状态代码。由于这些视图是ajax视图,这似乎有些不合适。我不希望用户在这种情况下登录,但我希望Django告诉客户端访问这样的视图需要身份验证(我认为401应该是正确的状态代码)。
为了实现这一点,我开始编写自己的装饰者login_required_ajax,但不知怎的,这超出了我的技能。这是我到目前为止所提出的:
def login_required_ajax(function=None,redirect_field_name=None):
"""
Just make sure the user is authenticated to access a certain ajax view
Otherwise return a HttpResponse 401 - authentication required
instead of the 302 redirect of the original Django decorator
"""
def _decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
return HttpResponse(status=401)
if function is None:
return _decorator
else:
return _decorator(function)
在视图上使用此装饰器时,一旦我尝试访问网站上的任何页面,我就会收到ViewDoesNotExist异常。
我首先想到的问题可能是当用户未经过身份验证时直接返回HttpResponse,因为响应对象不是可调用的。但是,只要我不尝试访问有问题的视图,装饰者应该工作,不应该吗?如果这真的是关键,我怎么能写一个返回状态代码为401的HttpResponse的装饰器?
答案 0 :(得分:16)
这是一次非常好的尝试。这是我发现的几个问题:
_decorator
函数应返回_wrapped_view
。if function is None
块的缩进有点偏离 - login_required_ajax
函数需要返回修饰函数。这是装饰者做出的改变:
def login_required_ajax(function=None,redirect_field_name=None):
"""
Just make sure the user is authenticated to access a certain ajax view
Otherwise return a HttpResponse 401 - authentication required
instead of the 302 redirect of the original Django decorator
"""
def _decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
return HttpResponse(status=401)
return _wrapped_view
if function is None:
return _decorator
else:
return _decorator(function)