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')#这里返回的可以自己再加
  • 相关阅读:
    02Spring注解开发
    01Spring配置文件
    网络编程
    CHIL-SQL-IN 操作符
    CHIL-SQL-通配符
    CHIL-SQL-LIKE 操作符
    CHIL-SQL-TOP 子句
    CHIL-SQL-DELETE 语句
    CHIL-SQL-UPDATE 语句
    CHIL-SQL-INSERT INTO 语句
  • 原文地址:https://www.cnblogs.com/guojieying/p/13964204.html
Copyright © 2011-2022 走看看