如何更改状态 JsonResponse 在 Django

My API 返回对象 JSON 错误时,但状态代码相等
HTTP 200

:


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


如何更改响应代码以指向错误?
已邀请:

董宝中

赞同来自:

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
https://docs.python.org/3/libr ... tatus
来自 Python
https://www.python.org/downloa ... -350/
进一步。 您可以在定义时使用它
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

. 您可以查看所有
https://www.iana.org/assignmen ... xhtml
国家代码 IANA 来自图书馆 python
https://docs.python.org/3/libr ... codes
.
</status_name>

卫东

赞同来自:

这个答案是OT。 Sayse 作品,但它无证。
https://github.com/django/djan ... 3L563
, 然后发现他传输了剩下的
**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/

要回复问题请先登录注册