方法一

1.1 自定义APIResponse类

重写父类Response方法,进入Response类查看源代码

class Response(SimpleTemplateResponse):
    """
    An HttpResponse that allows its data to be rendered into
    arbitrary media types.
    """

    def __init__(self, data=None, status=None,
                 template_name=None, headers=None,
                 exception=False, content_type=None):
        """
        Alters the init arguments slightly.
        For example, drop 'template_name', and instead use 'data'.

        Setting 'renderer' and 'media_type' will typically be deferred,
        For example being set automatically by the `APIView`.
        """
        super().__init__(None, status=status)

        if isinstance(data, Serializer):
            msg = (
                'You passed a Serializer instance as data, but '
                'probably meant to pass serialized `.data` or '
                '`.error`. representation.'
            )
            raise AssertionError(msg)

        self.data = data
        self.template_name = template_name
        self.exception = exception
        self.content_type = content_type

        if headers:
            for name, value in headers.items():
                self[name] = value

我们需要重写__init__方法

在utils包中新建工具类APIResponse.py,继承rest_framework.response.Response代码如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: 多点部落
@contact: wouldmissyou@163.com
@time: 2021/3/26 10:56 
@file: APIResponse.py
@desc: 
"""
from rest_framework.response import Response


class APIResponse(Response):
    def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False,
                 **kwargs):
        # data的初始状态:状态码和状态信息
        data = {
            'code': data_status,
            'message': data_msg,
        }
        # data的响应数据体
        # results可能是false、0等数据,这些数据某些情况下也会作为合法数据返回
        if results is not None:
            data['results'] = results
        # data响应的其他内容
        # if kwags is not None:
        #     for k, v in kwargs.items():
        #         setattr(data, k, v)
        data.update(kwargs)

        super().__init__(data=data, status=http_status, headers=headers, exception=exception)
        # 重写父类的__init__方法

1.2 在views.py中使用APIResponse

导入APIResponse

from utils.APIResponse import APIResponse

views.py中使用

class IndexBannerListView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        index_banners = IndexBanner.objects.all()
        serializer = IndexBannerSerializer(index_banners, many=True)
        # return Response({'data': serializer.data, 'message': '获取成功', 'code': 0})
        return APIResponse(0,results=serializer.data)

image-20210326110553457

方法二

自定义restful.py文件,继承rest_framework.response.Response代码如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: 多点部落
@contact: wouldmissyou@163.com
@time: 2021/3/26 11:11 
@file: restful.py
@desc: 
"""
from rest_framework.response import Response

class HttpCode(object):
    ok = 200
    paramserror = 400
    unauth = 401
    methoderror = 405
    servererror = 500


def result(code=HttpCode.ok, message='', data=None, kwargs=None):
    json_dict = {'code': code, 'message': message, 'data': data}

    if kwargs and isinstance(kwargs, dict) and kwargs.keys():
        json_dict.update(kwargs)

    return Response(json_dict)


# 请求正常
def ok(message='', data=None):
    return result(code=HttpCode.ok, message=message, data=data)


# 参数错误
def params_error(message='', data=None):
    return result(code=HttpCode.paramserror, message=message, data=data)


# 未登录
def unauth(message='', data=None):
    return result(code=HttpCode.unauth, message=message, data=data)


# 请求方法错误
def method_error(message='', data=None):
    return result(code=HttpCode.methoderror, message=message, data=data)


# 服务器错误
def server_error(message='', data=None):
    return result(code=HttpCode.servererror, message=message, data=data)

在视图中使用

from utils import restful


class IndexBannerListView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        index_banners = IndexBanner.objects.all()
        serializer = IndexBannerSerializer(index_banners, many=True)
        # return Response({'data': serializer.data, 'message': '获取成功', 'code': 0})
        return restful.ok(data=serializer.data)
    def post(self, request):
        serializer = IndexBannerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'data': serializer.data, 'message': '添加成功', 'code': 0})
        return restful.params_error(data=serializer.errors)

image-20210326111832538

本文作者:博主:
文章标题:DRF djangorestframework中封装Response响应类
本文地址:http://wouldmissyou.com/archives/78/     
版权说明:若无注明,本文皆为“多点部落”原创,转载请保留文章出处。
最后修改:2021 年 03 月 26 日 11 : 18 AM
如果觉得我的文章对你有用,请随意赞赏