Loading

自定义Response对象

背景

统一异常信息的返回格式.

安装rest_framework模块

pip install djangorestframework==3.10.3
image

将rest_framework模块注册到app应用列表中

# app应用列表
INSTALLED_APPS = [
    ...
    'rest_framework'
]

在utils.py文件下创建 api_response.py 响应模块

# 1. 继承rest_framework的Response响应模块, 自定义响应格式.
from rest_framework.response import Response


class ResponseDataFormat(Response):
    # 初始化 (展示的状态码, 信息, 数据, 状态码
    def __init__(self, code=200, msg='访问成功!', data=None, status=None,
                 template_name=None, headers=None, content_type=None, **kwargs):
        # 定义一个字典
        dic = {'code': code, 'msg': msg}

        # data属性有值则将值条件到字典中
        if data:
            dic.update({'data': data})

        # 如果有而外的参数如, token, 也将值添加到字典中 kwargs是一个字典类型的值, 没有值是{}, 更新不影响
        dic.update(kwargs)

        # 调用Response的__init__生成Response对象并初始化值, super()==> Response对象, 对象调用方法将自己作为第一个参数进行传递
        super().__init__(data=dic, status=status,
                         template_name=template_name, headers=headers, content_type=content_type)

image

posted @ 2022-12-01 23:26  爱learn  阅读(78)  评论(0编辑  收藏  举报