Python 如何在 Django 中更改 JsonResponse 的状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35059916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:55:49  来源:igfitidea点击:

How to change status of JsonResponse in Django

pythondjangotastypie

提问by Dhanushka Amarakoon

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?

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

采纳答案by Selcuk

JsonResponsenormally returns HTTP 200, which is the status code for 'OK'. In order to indicate an error, you can add an HTTP status code to JsonResponseas it is a subclass of HttpResponse:

JsonResponse通常返回HTTP 200,这是 的状态代码'OK'。为了指示错误,您可以添加一个 HTTP 状态代码,JsonResponse因为它是 的子类HttpResponse

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

回答by Sayse

Return an actual status

返回实际状态

JsonResponse(status=404, data={'status':'false','message':message})

回答by Pratik Gujarathi

To change status code in JsonResponseyou can do this :

要更改状态代码,JsonResponse您可以执行以下操作:

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

回答by Kushan Gunasekera

Python built-in http library has new class called HTTPStatuswhich is come from Python 3.5onward. You can use it when define a status.

Python 内置的 http 库有一个名为HTTPStatus 的新类,它来自Python 3.5以后。您可以在定义status.

from http import HTTPStatus
response = JsonResponse({'status':'false','message':message}, status=HTTPStatus.INTERNAL_SERVER_ERROR)

The value of HTTPStatus.INTERNAL_SERVER_ERROR.valueis 500. When someone read your code it's better define someting like HTTPStatus.<STATUS_NAME>other than define an integer value like 500. You can view all the IANA-registeredstatus codes from python library here.

HTTPStatus.INTERNAL_SERVER_ERROR.valueIS 500。当有人阅读您的代码时,最好定义类似的东西,HTTPStatus.<STATUS_NAME>而不是定义像500. 您可以在此处查看来自 python 库的所有IANA 注册状态代码。

回答by Benjamin Atkin

This answer from Sayse works but it's undocumented. If you look at the sourceyou find that it passes the remaining **kwargsto the superclass constructor, 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.

Sayse的这个答案有效,但没有记录。如果查看源代码,您会发现它将剩余部分传递**kwargs给超类构造函数 HttpStatus。但是在文档字符串中他们没有提到这一点。我不知道假设关键字 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)