drf--自定义封装返回response对象及猴子补丁概念
1.自定义封装response对象
1.1 自已2b版:太固定了很不好,没办法传原来response的其他参数
封装
class MyResponse(Response):
def __init__(self):
self.status = 100
self.msg = '成功'
@property
def get_dict(self):
return self.__dict__
使用
# 原来的写法
class Test(APIView):
def get(self, request):
response = {'status':'100', 'msg':None}
# 写逻辑
response['data'] = {'name':'egon', 'age':19}
return Response(response)
# low版使用
from app01.utils.response import Myresponse
class Test(APIView):
def get(self, request):
response = Myresponse()
# 写逻辑
response.status = 101
response.msg = '失败'
response.data = {'name': 'egon', 'age': 19}
return Response(response)
1.2 老师高级通用版
封装
from rest_framework.response import Response
class APIResponse(Response):
def __init__(self, code=100, msg='成功', data=None, status=None, headers=None, **kwargs):
dic = {'code': code, 'msg': msg}
if data:
dic['data'] = data
dic.update(kwargs) # 可以灵活的添加,需要返回的键值对
super().__init__(data=dic, status=status, headers=headers)
使用
return APIResponse(100,'成功',book_ser.data)
return APIResponse(101,'验证失败',book_ser.errors)
猴子补丁
# 程序运行的过程中,动态的替换对象的属性或方法