【发布时间】:2016-05-05 17:39:39
【问题描述】:
我的 API 出错时返回 JSON 对象,但状态代码为 HTTP 200:
response = JsonResponse({'status': 'false', 'message': message})
return response
如何更改响应代码以指示错误?
【问题讨论】:
标签: python python-3.x django python-2.7 tastypie
我的 API 出错时返回 JSON 对象,但状态代码为 HTTP 200:
response = JsonResponse({'status': 'false', 'message': message})
return response
如何更改响应代码以指示错误?
【问题讨论】:
标签: python python-3.x django python-2.7 tastypie
JsonResponse 通常返回HTTP 200,这是'OK' 的状态码。为了指示错误,您可以将 HTTP 状态代码添加到 JsonResponse,因为它是 HttpResponse 的子类:
response = JsonResponse({'status':'false','message':message}, status=500)
【讨论】:
返回一个实际状态
JsonResponse(status=404, data={'status':'false','message':message})
【讨论】:
要更改JsonResponse 中的状态码,您可以这样做:
response = JsonResponse({'status':'false','message':message})
response.status_code = 500
return response
【讨论】:
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库here查看所有IANA-registered状态码。
【讨论】:
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)
【讨论】: