How to change status of JsonResponse in Django

前端 未结 5 381
感情败类
感情败类 2021-02-03 16:35

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

response = JsonResponse({\'status         


        
5条回答
  •  滥情空心
    2021-02-03 17:14

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

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

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

提交回复
热议问题