restframework 自定义json返回格式

前言

  • rest_framework本身自带的Respone类已经很好的支持JSON返回格式了
    但我们需要每次都在视图定义字典{"cdoe": 1, "msg": "Success", "data": data}就会显得很麻烦
    所以我们定义一个类去继承Respone类,并返回我们自定义的格式。
  • 具体的思路已经忘了,后续如果还能记起来再回来补充。

代码实现

from rest_framework.response import Response


class JSonResponse(Response):
    def __init__(self, code=1, msg="Success", data="", status=None,
                 template_name=None, headers=None,
                 exception=False, content_type=None):

        super(JSonResponse, self).__init__(data, status, template_name, headers,
                                           exception, content_type)

        self.data = {"code": code, "msg": msg, "data": data}
原文地址:https://www.cnblogs.com/se7enjean/p/13187336.html