我的API在出错时返回JSON对象,但状态代码为HTTP 200
:
response = JsonResponse({'status': 'false', 'message': message})
return response
如何更改响应代码以指示错误?
答案 0 :(得分:95)
JsonResponse
通常会返回HTTP 200
,这是'OK'
的状态代码。为了表明错误,您可以将HTTP状态代码添加到JsonResponse
,因为它是HttpResponse
的子类:
response = JsonResponse({'status':'false','message':message}, status=500)
答案 1 :(得分:11)
返回实际状态
JsonResponse(status=404, data={'status':'false','message':message})
答案 2 :(得分:6)
要更改JsonResponse
中的状态代码,您可以执行以下操作:
response = JsonResponse({'status':'false','message':message})
response.status_code = 500
return response
答案 3 :(得分:0)
Python内置的http库具有一个名为HTTPStatus的新类,该类从Python 3.5开始。您可以在定义status
时使用它。
from http import HTTPStatus
response = JsonResponse({'status':'false','message':message}, status=HTTPStatus.INTERNAL_SERVER_ERROR)
HTTPStatus.INTERNAL_SERVER_ERROR.value
的值为500
。当有人阅读您的代码时,最好定义诸如HTTPStatus.<STATUS_NAME>
之类的东西,而不是定义诸如500
之类的整数值。您可以从python库IANA-registered中查看所有here状态代码。
答案 4 :(得分:0)
这个来自Sayse的答案有效,但没有记录。 If you look at the source会发现它会将其余的**kwargs
传递给超类构造函数HttpStatus。但是在文档字符串中,他们没有提及。我不知道将关键字args传递给超类构造函数是否是惯例。
您也可以像这样使用它:
JsonResponse({"error": "not found"}, status=404)
我做了一个包装纸
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)