drf自己封装response

from rest_framework.response import Response

# 第一种
class APIResponse(Response):
    def __init__(self, code=100, msg='成功', status=None, headers=None, **kwargs):
        res_data = {
            'code': code,
            'msg': msg,
        }
        if kwargs:
            res_data.update(kwargs)
        super().__init__(data=res_data, status=status, headers=headers)     

'''
        return APIResponse()  
    	# 成功,没有数据  
        {
            "code": 100,
            "msg": "成功"
        }
        
        return APIResponse(result=[])  
        {
            "code": 100,
            "msg": "成功"
             result:[]
        }
        
        return APIResponse(token='xxxxx')  
        {
            "code": 100,
            "msg": "成功"
            token:'xxxxx'
        }
        
         return APIResponse(headers={name:amgl})  
        # 响应头中会多name=amgl
        {
            "code": 100,
            "msg": "成功"
        }
'''
# 第二种
# class MyResponse():
#     def __init__(self):
#         self.status=100
#         self.msg='成功'
#     @property
#     def get_dict(self):
#         return self.__dict__

# if __name__ == '__main__':
#     res=MyResponse()
#     res.status=101
#     res.msg='查询失败'
#     # res.data={'name':'AAA'}
#     print(res.get_dict) # {'status': 101, 'msg': '查询失败'}
posted @ 2022-11-02 09:21  阿木古冷  阅读(64)  评论(1编辑  收藏  举报