而不是这样做:
res = HttpResponse("Unauthorized")
res.status_code = 401
return res
Run Code Online (Sandbox Code Playgroud)
有没有办法在不打字的情况下每次都这样做?
Stu*_*Cox 124
我知道这是一个旧的,但它是"django 401"的谷歌搜索结果,所以我想我会指出这一点......
假设您已经导入django.http.HttpResponse,可以在一行中完成:
return HttpResponse('Unauthorized', status=401)
Run Code Online (Sandbox Code Playgroud)
该'Unauthorized'字符串是可选的.简单.
class HttpResponseUnauthorized(HttpResponse):
def __init__(self):
self.status_code = 401
...
return HttpResponseUnauthorized()
Run Code Online (Sandbox Code Playgroud)
class HttpResponseUnauthorized(HttpResponse):
status_code = 401
...
return HttpResponseUnauthorized()
Run Code Online (Sandbox Code Playgroud)
通常,您应该设置实例,__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
Run Code Online (Sandbox Code Playgroud)
继承解决方案
from django.http import HttpResponse
class Http401(HttpResponse):
def __init__(self):
super().__init__('401 Unauthorized', status=401)
Run Code Online (Sandbox Code Playgroud)
在 autil.py中替换多次调用:
return HttpResponse('401 Unauthorized', status=401)
Run Code Online (Sandbox Code Playgroud)
有趣的是,1.9.6 https://github.com/django/django/blob/1.9.6/django/http/response.py#L443 中还有其他命名响应,但不是 401。
| 归档时间: |
|
| 查看次数: |
31635 次 |
| 最近记录: |