drf中save以及response的源码分析

一.save

其中比较重要的源码

 if self.instance is not None:
            self.instance = self.update(self.instance, validated_data)
            assert self.instance is not None, (
                '`update()` did not return an object instance.'
            )
        else:
            self.instance = self.create(validated_data)
            assert self.instance is not None, (
                '`create()` did not return an object instance.'
            )

        return self.instance

这里很明显就可以看出save我们传参instance的由于决定了他后续是运行create还是updata方法

二、response

涉及其中的参数的源码

#传入的参数
def __init__(self, data=None, status=None,
                 template_name=None, headers=None,
                 exception=False, content_type=None):
    
#他对于参数进行的赋值
        self.data = data
        self.template_name = template_name
        self.exception = exception
        self.content_type = content_type
    
data:响应的数据 - 空、字符串、数字、列表、字段、布尔
status:网络状态码
template_name:drf说自己也可以支持前后台不分离返回页面,但是不能和data共存(不会涉及)
headers:响应头(不用刻意去管)
exception:是否是异常响应(如果是异常响应,可以赋值True,没什么用)
content_type:响应的结果类型(如果是响应data,默认就是application/json,所以不用管)

常见使用

Response(
    data={
        'status': 0,
        'msg': 'ok',
        'result': '正常数据'
    }
)

Response(
    data={
        'status': 1,
        'msg': '客户端错误提示',
    },
    status=status.HTTP_400_BAD_REQUEST,
    exception=True
)

 我们通过类的继承修改Response源码:

新建response.py文件

from rest_framework.response import Response

class APIResponse(Response):
    def __init__(self, status=0, msg='ok', http_status=None, headers=None, exception=False, **kwargs):
        # 将外界传入的数据状态码、状态信息以及其他所有额外存储在kwargs中的信息,都格式化成data数据
        data = {
            'status': status,
            'msg': msg
        }
        # 在外界数据可以用result和results来存储
        if kwargs:
            data.update(kwargs)

        super().__init__(data=data, status=http_status, headers=headers, exception=exception)


# 使用:
# APIResponse() 代表就返回 {"status": 0, "msg": "ok"}

# APIResponse(result="结果") 代表返回 {"status": 0, "msg": "ok", "result": "结果"}

# APIResponse(status=1, msg='error', http_status=400, exception=True) 异常返回 {"status": 1, "msg": "error"}
原文地址:https://www.cnblogs.com/baohanblog/p/12332951.html