Python 如何在 Django 中返回 401 Unauthorized?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4356842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:24:43  来源:igfitidea点击:

How do I return a 401 Unauthorized in Django?

pythondjango

提问by TIMEX

Instead of doing this:

而不是这样做:

res = HttpResponse("Unauthorized")
res.status_code = 401
return res

Is there a way to do it without typing it every time?

有没有办法不用每次都打字?

回答by Ignacio Vazquez-Abrams

Write a view decorator that checks the appropriate HTTP headers and returns the appropriate response (there is no built-in typefor response code 401).

编写一个视图装饰器来检查适当的 HTTP 标头并返回适当的响应(响应代码 401没有内置类型)。

回答by Glenn Maynard

class HttpResponseUnauthorized(HttpResponse):
    def __init__(self):
        self.status_code = 401

...
return HttpResponseUnauthorized()

回答by Stu Cox

I know this is an old one, but it's the top Google result for "django 401", so I thought I'd point this out...

我知道这是一个旧的,但它是“django 401”的最高谷歌结果,所以我想我会指出这一点......

Assuming you've already imported django.http.HttpResponse, you can do it in a single line:

假设您已经 import django.http.HttpResponse,您可以在一行中完成:

return HttpResponse('Unauthorized', status=401)

The 'Unauthorized'string is optional. Easy.

'Unauthorized'字符串是可选的。简单。

回答by Wilfred Hughes

class HttpResponseUnauthorized(HttpResponse):
    status_code = 401

...
return HttpResponseUnauthorized()

Normally, you should set the instance in __init__or you end up with class variables that are shared between all instances. However, Django does this for you already:

通常,您应该设置实例,__init__否则您最终会得到在所有实例之间共享的类变量。但是,Django 已经为您做到了:

class HttpResponse(object):
    """A basic HTTP response, with content and dictionary-accessed headers."""

    status_code = 200

    def __init__(self, content='', mimetype=None, status=None,
            content_type=None):
        # snip...
        if status:
            self.status_code = status

(see the Django code in context)

请参阅上下文中的 Django 代码