Django REST framework custom format for all out responses

后端 未结 2 1342
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 16:00

In my project I use DRF as backend and Angular as frontend.

Django==1.10 djangorestframework==3.7.1

I need all responses from DRF to be in the following format.

2条回答
  •  终归单人心
    2021-02-15 16:46

    This would be more a more robust solution, as it can be used with Generic Views hassle free.

    Also, the checks in render() can be easily altered as per the needs (Eg., handling no-2XX in this solution).

    from rest_framework.renderers import JSONRenderer
    
    
    class CustomRenderer(JSONRenderer):
    
        def render(self, data, accepted_media_type=None, renderer_context=None):
            status_code = renderer_context['response'].status_code
            response = {
              "status": "success",
              "code": status_code,
              "data": data,
              "message": None
            }
    
            if not str(status_code).startswith('2'):
                response["status"] = "error"
                response["data"] = None
                try:
                    response["message"] = data["detail"]
                except KeyError:
                    response["data"] = data
    
            return super(CustomRenderer, self).render(response, accepted_media_type, renderer_context)
    
    

提交回复
热议问题