Django JSON响应错误状态

时间:2016-01-28 11:12:34

标签: python django tastypie

我的API在出错时返回JSON对象,但状态代码为HTTP 200

response = JsonResponse({'status': 'false', 'message': message})
return response

如何更改响应代码以指示错误?

5 个答案:

答案 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)