gpt4 book ai didi

ajax - ajax View 上的 login_required 装饰器返回 401 而不是 302

转载 作者:行者123 更新时间:2023-12-03 23:42:02 25 4
gpt4 key购买 nike

在编写一些 View 来响应 ajax 请求时,我发现 login_required 装饰器总是为未通过身份验证的用户返回 302 状态代码,这有点奇怪。由于这些 View 是 ajax View ,这似乎有些不合适。我不希望用户在这种情况下登录,但我希望 Django 告诉客户端访问这样的 View 需要身份验证(我认为 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)

在 View 上使用此装饰器时,只要我尝试访问站点上的任何页面,就会收到 ViewDoesNotExist 异常。

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

最佳答案

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

  • 您的 _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)

    关于ajax - ajax View 上的 login_required 装饰器返回 401 而不是 302,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10031001/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com