Bootstrap

自定义 rest_framework 响应返回格式

# # settings.py

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'utils.custom_render.CustomRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    )
}
# # custom_render.py

from rest_framework.renderers import JSONRenderer


# 导入控制返回的JSON格式的类
class CustomRenderer(JSONRenderer):
    # 重构render方法
    def render(self, data, accepted_media_type=None, renderer_context=None):
        if renderer_context:
            # 判断实例的类型,返回的数据可能是列表也可能是字典
            if isinstance(data, dict):
                # 如果是字典的话应该是返回的数据,会包含msg,code,status等字段必须抽离出来
                msg = data.pop('msg', '请求成功')
                code = data.pop('code', renderer_context["response"].status_code)
            else:
                msg = '请求成功'
                code = renderer_context["response"].status_code

            # 自定义返回数据格式
            ret = {
                'code': code,
                'msg': msg,
                'data':  data,
            }
            # 返回JSON数据
            return super().render(ret, accepted_media_type, renderer_context)
        else:
            return super().render(data, accepted_media_type, renderer_context)

或 自定义Response

# # custom_response.py

from rest_framework import status
from rest_framework.views import Response


class CustomResponse(Response):

    def __init__(self, code=200, msg="成功", data=None, status=status.HTTP_200_OK, **kwargs):
        back_info_dict = {"code": code, "msg": msg, data: []}
        if data:
            back_info_dict.update(data=data)
        back_info_dict.update(kwargs)
        super().__init__(data=back_info_dict, status=status)

;