封装 Response

Response 封装

代码展示

# 新建文件: utils/response.py

from rest_framework.response import Response

class MyResponse(Response):
    # http响应状态码, headers响应头
    def __init__(self, code='100', msg='成功', status=None, headers=None, **kwargs):
        data = {'code': code, 'msg': msg}
        if kwargs:
            data.update(kwargs)
        super().__init__(data=data, status=status, headers=headers)

使用

# 在 views.py 中使用----->本质上就是 Response

from utils.common_response import MyResponse
class TestResponseView(APIView):
    def get(self, request):

        # 以下不同的情况使用
        return MyResponse(token='ss.ee.ss',icon='/media/icon/default.png')
        return MyResponse(msg='创建成功')
        return MyResponse(msg='用户不存在',code=101)
        return MyResponse(results=[{},{}])
        return MyResponse(headers={'xx': 'yy'})

        # {code:999,msg:用户名或密码错误}
        raise MyResponse(detail='用户名或密码错误')
posted @ 2023-04-18 16:06  codegjj  阅读(26)  评论(0编辑  收藏  举报