login_required ajax 视图上的装饰器返回 401 而不是 302



在编写一些视图来响应 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)

在视图上使用此装饰器时,一旦我尝试访问网站上的任何页面,我就会收到 ViewDoesNotExists 异常。

我最初认为问题可能是在用户未经过身份验证时直接返回 HttpResponse,因为响应对象不是可调用对象。但是,只要我不尝试访问有问题的视图,装饰器就应该工作,不是吗?如果这真的是关键,我如何编写一个返回状态代码为 401 的 HttpResponse 的装饰器?

这是一个很好的尝试。以下是我发现的几个问题:

  1. 您的_decorator函数应返回_wrapped_view
  2. 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)

相关内容

最新更新