restframework 自定义返回响应格式

代码实现

只需要继承rest_framework.responseResponse,重写self.data即可

from rest_framework.response import Response


class MyResponse(Response):
    def __init__(self, code=10000, msg="Success", data="", status=None,
                 template_name=None, headers=None,
                 exception=False, content_type=None):
        super(MyResponse, self).__init__(data, status, template_name, headers,
                                         exception, content_type)

        self.data = {"code": code, "msg": msg, "data": data}

在视图中调用

# 自定义的响应返回格式类
from libs.success import MyResponse


class Login(APIView):
    authentication_classes = []

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(phone=username).first()
        if user and user.check_pwd(password):
            r_dict = {'token': create_token({'user_id': user.id})}
            add_user.delay(username)

            con = get_redis_connection("default")
            con.set('token', create_token({'user_id': user.id}), 60)
            return MyResponse(data=r_dict)
        # 通过传入参数比如http状态码(status=301)
        return MyResponse(code=40000, msg="账号或密码错误", data='' status=301)

正常参数

异常参数

原文地址:https://www.cnblogs.com/se7enjean/p/13714267.html