[英]How to change status of JsonResponse in Django
My API is returning a JSON object on error but the status code is HTTP 200
:我的 API 在出错时返回一个 JSON 对象,但状态代码是
HTTP 200
:
response = JsonResponse({'status': 'false', 'message': message})
return response
How can I change the response code to indicate an error?如何更改响应代码以指示错误?
JsonResponse
normally returns HTTP 200
, which is the status code for 'OK'
. JsonResponse
通常返回HTTP 200
,这是'OK'
的状态代码。 In order to indicate an error, you can add an HTTP status code to JsonResponse
as it is a subclass of HttpResponse
:为了指示错误,您可以向
JsonResponse
添加 HTTP 状态代码,因为它是HttpResponse
的子类:
response = JsonResponse({'status':'false','message':message}, status=500)
返回实际状态
JsonResponse(status=404, data={'status':'false','message':message})
To change status code in JsonResponse
you can do this :要更改
JsonResponse
状态代码,您可以执行以下操作:
response = JsonResponse({'status':'false','message':message})
response.status_code = 500
return response
Python built-in http library has new class called HTTPStatus which is come from Python 3.5 onward. Python 内置的 http 库有一个名为HTTPStatus 的新类,它来自Python 3.5以后。 You can use it when define a
status
.您可以在定义
status
时使用它。
from http import HTTPStatus
response = JsonResponse({'status':'false','message':message}, status=HTTPStatus.INTERNAL_SERVER_ERROR)
The value of HTTPStatus.INTERNAL_SERVER_ERROR.value
is 500
. HTTPStatus.INTERNAL_SERVER_ERROR.value
值为500
。 When someone read your code it's better define someting like HTTPStatus.<STATUS_NAME>
other than define an integer value like 500
.当有人阅读您的代码时,最好定义一些类似
HTTPStatus.<STATUS_NAME>
而不是定义一个像500
这样的整数值。 You can view all the IANA-registered status codes from python library here .您可以 在此处查看来自 python 库的所有IANA 注册状态代码。
This answer from Sayse works but it's undocumented. Sayse的这个答案有效,但没有记录。 If you look at the source you find that it passes the remaining
**kwargs
to the superclass constructor, HttpStatus. 如果查看源代码,您会发现它将剩余的
**kwargs
传递给超类构造函数 HttpStatus。 However in the docstring they don't mention that.但是在文档字符串中他们没有提到这一点。 I don't know if it's the convention to assume that keyword args will be passed to the superclass constructor.
我不知道假设关键字 args 将传递给超类构造函数是否是惯例。
You can also use it like this:你也可以这样使用它:
JsonResponse({"error": "not found"}, status=404)
I made a wrapper:我做了一个包装:
from django.http.response import JsonResponse
class JsonResponseWithStatus(JsonResponse):
"""
A JSON response object with the status as the second argument.
JsonResponse passes remaining keyword arguments to the constructor of the superclass,
HttpResponse. It isn't in the docstring but can be seen by looking at the Django
source.
"""
def __init__(self, data, status=None, encoder=DjangoJSONEncoder,
safe=True, json_dumps_params=None, **kwargs):
super().__init__(data, encoder, safe, json_dumps_params, status=status, **kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.