首页 > 其他分享 >封装Response对象

封装Response对象

时间:2022-12-10 21:11:12浏览次数:30  
标签:code 封装 对象 msg kwargs CommonResponse data Response

封装Response对象

#utils.py
#自定制响应
from rest_framework.response import Response

class CommonResponse(Response):
    def __init__(self, code=10, msg='成功', data=None, **kwargs):
        dic = {'code': code, 'msg': msg, 'data': data}
        if data:
            dic = {'code': code, 'msg': msg, 'data': data}
        dic.update(kwargs)
        super().__init__(data=dic, status=None, headers=None, )
#urls.py
path('test7/', views.Test7View.as_view()),

#views.py
from app01.utils import CommonResponse
class Test7View(APIView):
    def get(self, request, *args, **kwargs):
        return CommonResponse(data={'name':'zhao'},demo='kfdha',token='fldksjafld')

image-20221210124805607

#views.py
from app01.utils import CommonResponse
class Test7View(APIView):
    def get(self, request, *args, **kwargs):
       
        return CommonResponse(token='fldksjafld')

image-20221210124855617

class Test7View(APIView):
    def get(self, request, *args, **kwargs):
   
        return CommonResponse(code=101,msg='错误',data={'name':'lisi'},aa='falkda')

image-20221210125027179

标签:code,封装,对象,msg,kwargs,CommonResponse,data,Response
From: https://www.cnblogs.com/zaosong/p/16972335.html

相关文章