zoukankan      html  css  js  c++  java
  • drf—— 封装Response对象

    1.工具类中写utils.py

    # 使用自己封装的response
    from rest_framework.response import Response
    class APIResponse(Response):
        def __init__(self, code=100, msg='成功', data=None, status=None, headers=None, content_type=None, **kwargs):
            dic = {'code': code, 'msg': msg}
            if data:
                dic['data'] = data
    
            dic.update(kwargs) # 这里使用update更新
            super().__init__(data=dic, status=status,
                             template_name=None, headers=headers,
                             exception=False, content_type=content_type)

     2.views.py 使用

    from app01.utils import APIResponse
    class StudentApiView(APIView):
        #这样写麻烦
        # def get(self,request):
        #     res={'code':100,'msg':'成功','data':None}
        #     student_list=Student.objects.all()
        #     ser=StudentSerializer(student_list,many=True)
        #
        #     res['data']=ser.data
        #     return Response(res)
        #简单写法
        def get(self, request):
            student_list = Student.objects.all()
            ser = StudentSerializer(student_list, many=True)
            return APIResponse(code=100,msg='查询成功',data=ser.data,count=200,next='http://wwwa.asdfas')#这里返回的可以自己再加
  • 相关阅读:
    前缀和
    不用加减乘除做加法
    数组中重复的数字
    滑动窗口的最大值
    矩阵中的路径
    Redis 和 Memcached 的区别 Tair
    机器人的运动范围
    汉诺塔问题
    洗牌算法
    斐波那契查找算法(黄金分割查找算法)
  • 原文地址:https://www.cnblogs.com/guojieying/p/13964204.html
Copyright © 2011-2022 走看看