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
How do I return a 401 Unauthorized in Django?
提问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

