如何在Django中更改JsonResponse的状态 [英] How to change status of JsonResponse in Django

查看:469
本文介绍了如何在Django中更改JsonResponse的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的API错误返回一个JSON对象,但状态代码为 HTTP 200

My API is returning a JSON object on error but the status code is HTTP 200:

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

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

How can I change the response code to indicate an error?

推荐答案

JsonResponse 通常返回 HTTP 200 ,这是的状态代码确定 。为了指示错误,您可以将HTTP状态代码添加到 JsonResponse ,因为它是 HttpResponse 的子类:

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

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

这篇关于如何在Django中更改JsonResponse的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆