drf中二次封装Response
在app文件夹下新建response.py文件
# 面向对象二次封装Response
from rest_framework.response import Response
class APIResponse(Response):
# 格式化data
def __init__(self, status=1000, msg='ok',
results=None, http_status=None, headers=None, exception=False, **kwargs):
data = {
'status': status,
'msg': msg
}
if results is not None:
data['results'] = results
data.update(**kwargs) # 将传入的其他数据放入data字典
# 处理完毕数据后,剩下的过程还是丢给Response类中的init做完
super(APIResponse, self).__init__(
data=data, status=http_status, headers=headers, exception=exception)
然后在view中导入response.py中的自建类APIResponse,传参使用
return APIResponse(2001,'单查error')
return APIResponse(results=car_data)