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')#这里返回的可以自己再加
  • 相关阅读:
    手动安装mysql
    spring boot 配置注入
    IOS-电话拦截
    重新入坑-IntelliJ Maven
    git使用问题
    Intelij U
    iTunes空间不足无法备份iphone的问题
    Centos7最小化安装
    实操笔记
    centos7中端口及服务对应情况(笔记)
  • 原文地址:https://www.cnblogs.com/guojieying/p/13964204.html
Copyright © 2011-2022 走看看