自定义Response

应用下新建utils文件,在里面定义自己的Response类,继承自Response

# 导入Response
from rest_framework.response import Response

# 自定义的Response类
class APIResponse(Response):
    # 初始化属性
    def __init__(self, code=100, msg='成功', data=None, status=None, headers=None, **kwargs):  #  **kwargs用于接受其他的自定义数据
        dic = {'code': code, 'msg': msg}
        if data:
            dic = {'code': code, 'msg': msg, 'data': data}
        else:
            dic.update(kwargs)
        super().__init__(data=dic, status=status, headers=headers)
-views.py

# 自定义的response
from app01.utils import APIResponse

class APIViewresponse(GenericAPIView):
    queryset = Books.objects.all()
    serializer_class = BookSerializer

    def get(self, request):
        book_list = self.get_queryset()
        book_ser = self.get_serializer(book_list, many=True)
        return APIResponse(100, '成功', book_ser.data)  # code,msg,data就可以随意定制

 

posted @ 2020-07-10 19:16  三根烦恼丝啊  阅读(721)  评论(0编辑  收藏  举报