Django之DRF源码分析(二)---数据校验部分

is_valid() 源码

def is_valid(self, raise_exception=False):
assert not hasattr(self, 'restore_object'), (
'Serializer `%s.%s` has old-style version 2 `.restore_object()` '
'that is no longer compatible with REST framework 3. '
'Use the new-style `.create()` and `.update()` methods instead.' %
(self.__class__.__module__, self.__class__.__name__)
) assert hasattr(self, 'initial_data'), (
'Cannot call `.is_valid()` as no `data=` keyword argument was '
'passed when instantiating the serializer instance.'
) if not hasattr(self, '_validated_data'):
try:
self._validated_data = self.run_validation(self.initial_data)
except ValidationError as exc:
self._validated_data = {}
self._errors = exc.detail
else:
self._errors = {} if self._errors and raise_exception:
raise ValidationError(self.errors) return not bool(self._errors)

serializers.py

    def run_validation(self, data=empty):
"""
We override the default `run_validation`, because the validation
performed by validators and the `.validate()` method should
be coerced into an error dictionary with a 'non_fields_error' key.
我们覆盖默认的“run_validation”,因为验证器和“.validate()”方法执行的验证应该强制到一个带有“non_fields_error”键的错误字典中。
"""
(is_empty_value, data) = self.validate_empty_values(data)
if is_empty_value:
return data
# 局部钩子校验
value = self.to_internal_value(data)
try:
self.run_validators(value)
# 全局钩子校验
value = self.validate(value)
assert value is not None, '.validate() should return the validated data'
except (ValidationError, DjangoValidationError) as exc:
raise ValidationError(detail=as_serializer_error(exc)) return value """>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"""
def to_internal_value(self, data):
"""
Dict of native values <- Dict of primitive datatypes.
"""
if not isinstance(data, Mapping):
message = self.error_messages['invalid'].format(
datatype=type(data).__name__
)
raise ValidationError({
api_settings.NON_FIELD_ERRORS_KEY: [message]
}, code='invalid') ret = OrderedDict()
errors = OrderedDict()
fields = self._writable_fields for field in fields:
validate_method = getattr(self, 'validate_' + field.field_name, None)
primitive_value = field.get_value(data)
try:
validated_value = field.run_validation(primitive_value)
if validate_method is not None:
validated_value = validate_method(validated_value)
except ValidationError as exc:
errors[field.field_name] = exc.detail
except DjangoValidationError as exc:
errors[field.field_name] = get_error_detail(exc)
except SkipField:
pass
else:
set_value(ret, field.source_attrs, validated_value) if errors:
raise ValidationError(errors) return ret """>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"""
def validate(self, attrs):
return attrs

fileds.py

    def validate_empty_values(self, data):
"""
Validate empty values, and either: * Raise `ValidationError`, indicating invalid data.
* Raise `SkipField`, indicating that the field should be ignored.
* Return (True, data), indicating an empty value that should be
returned without any further validation being applied.
* Return (False, data), indicating a non-empty value, that should
have validation applied as normal.
"""
if self.read_only:
return (True, self.get_default()) if data is empty:
if getattr(self.root, 'partial', False):
raise SkipField()
if self.required:
self.fail('required')
return (True, self.get_default()) if data is None:
if not self.allow_null:
self.fail('null')
return (True, None) return (False, data) def run_validation(self, data=empty):
"""
Validate a simple representation and return the internal value. The provided data may be `empty` if no representation was included
in the input. May raise `SkipField` if the field should not be included in the
validated data.
"""
(is_empty_value, data) = self.validate_empty_values(data)
if is_empty_value:
return data
value = self.to_internal_value(data)
self.run_validators(value)
return value def run_validators(self, value):
"""
Test the given value against all the validators on the field,
and either raise a `ValidationError` or simply return.
"""
errors = []
for validator in self.validators:
if hasattr(validator, 'set_context'):
validator.set_context(self) try:
validator(value)
except ValidationError as exc:
# If the validation error contains a mapping of fields to
# errors then simply raise it immediately rather than
# attempting to accumulate a list of errors.
if isinstance(exc.detail, dict):
raise
errors.extend(exc.detail)
except DjangoValidationError as exc:
errors.extend(get_error_detail(exc))
if errors:
raise ValidationError(errors) def to_internal_value(self, data):
"""
Transform the *incoming* primitive data into a native value.
"""
raise NotImplementedError(
'{cls}.to_internal_value() must be implemented.'.format(
cls=self.__class__.__name__
)
) def to_representation(self, value):
"""
Transform the *outgoing* native value into primitive data.
"""
raise NotImplementedError(
'{cls}.to_representation() must be implemented for field '
'{field_name}. If you do not need to support write operations '
'you probably want to subclass `ReadOnlyField` instead.'.format(
cls=self.__class__.__name__,
field_name=self.field_name,
)
)

Django之DRF源码分析(二)---数据校验部分的更多相关文章

  1. Django搭建及源码分析(二)

    上节针对linux最小系统,如何安装Django,以及配置简单的Django环境进行了说明. 本节从由Django生成的manage.py开始,分析Django源码.python版本2.6,Djang ...

  2. Django之DRF源码分析(四)---频率认证组件

    核心源码 def check_throttles(self, request): """ Check if request should be throttled. Ra ...

  3. Django与drf 源码视图解析

    0902自我总结 Django 与drf 源码视图解析 一.原生Django CBV 源码分析:View """ 1)as_view()是入口,得到view函数地址 2) ...

  4. Django搭建及源码分析(三)---+uWSGI+nginx

    每个框架或者应用都是为了解决某些问题才出现旦生的,没有一个事物是可以解决所有问题的.如果觉得某个框架或者应用使用很不方便,那么很有可能就是你没有将其使用到正确的地方,没有按开发者的设计初衷来使用它,当 ...

  5. Fresco 源码分析(二) Fresco客户端与服务端交互(1) 解决遗留的Q1问题

    4.2 Fresco客户端与服务端的交互(一) 解决Q1问题 从这篇博客开始,我们开始讨论客户端与服务端是如何交互的,这个交互的入口,我们从Q1问题入手(博客按照这样的问题入手,是因为当时我也是从这里 ...

  6. HDFS源码分析之数据块及副本状态BlockUCState、ReplicaState

    关于数据块.副本的介绍,请参考文章<HDFS源码分析之数据块Block.副本Replica>. 一.数据块状态BlockUCState 数据块状态用枚举类BlockUCState来表示,代 ...

  7. 十、Spring之BeanFactory源码分析(二)

    Spring之BeanFactory源码分析(二) 前言 在前面我们简单的分析了BeanFactory的结构,ListableBeanFactory,HierarchicalBeanFactory,A ...

  8. Vue源码分析(二) : Vue实例挂载

    Vue源码分析(二) : Vue实例挂载 author: @TiffanysBear 实例挂载主要是 $mount 方法的实现,在 src/platforms/web/entry-runtime-wi ...

  9. 框架-springmvc源码分析(二)

    框架-springmvc源码分析(二) 参考: http://www.cnblogs.com/leftthen/p/5207787.html http://www.cnblogs.com/leftth ...

随机推荐

  1. jsonp原理,跨域请求头处理

    一.jsonp(解决跨域)思路介绍: 因浏览器的同源策略不会拦截link标签内的src请求,所以利用这一点,我们把后端开放的接口路径放在src内, 其在发送请求后会自动接收返回的东西,所以我们可以给要 ...

  2. 【BZOJ3837】[PA2013]Filary

    [BZOJ3837][PA2013]Filary 题面 darkbzoj 题解 考虑到模数为\(2\)时答案至少为\(\frac n2\),这是我们答案的下界. 那么我们对于任意的一个数,它们答案集合 ...

  3. TensorFlow常用激活函数及其特点和用法(6种)详解

    http://c.biancheng.net/view/1911.html 每个神经元都必须有激活函数.它们为神经元提供了模拟复杂非线性数据集所必需的非线性特性.该函数取所有输入的加权和,进而生成一个 ...

  4. .NET三层架构开发初步

    转自:https://www.cnblogs.com/weilengdeyu/archive/2013/01/04/2844847.html 今天咱们来谈下三层架构.说到三层架构,搞过点程序的可能都知 ...

  5. 熟悉 rsync 的功能及其特点

    提要 熟悉 rsync 的功能及其特点 掌握 rsync 语法及常用选项的功能 掌握 rsync 命令的三种基本使用方法 掌握如何筛选 rsync 的传输目标 掌握使用 rsync 进行镜像和增量备份 ...

  6. [算法模板]SOS DP

    [算法模板]SOS DP 正文 SOS-DP(\(\text{Sum over Subsets}\))是用来解决这样的问题的: 其实就是子集和DP.上面每个\(F[mask]\)里面包含了\(mask ...

  7. 【WebTerminal】gotty工具

    ./gotty -w -p 8888 --permit-arguments /bin/sh ./gotty -w -p 8888 --permit-arguments  docker exec -ti ...

  8. Zookeeper的介绍与基本部署

    目录 简介 架构 安装 StandAlone模式 1. 安装 2. 修改配置 3. 启动 4. 验证 5. 基本用法 Distributed模式 1. 配置hosts 2. 配置zoo.cfg 3. ...

  9. 【洛谷】P1478 陶陶摘苹果(升级版)-全AC题解

    #include <iostream> #include <algorithm> using namespace std; int main() { int n,s,a,b; ...

  10. DDR3(2):初始化

    调取 DDR3 IP核后,是不能直接进行读写测试的,必须先进行初始化操作,对 IP 核进行校验.本篇采用 Modelsim 软件配合 DDR3 IP核生成的仿真模型,搭建出 IP核的初始化过程. 一. ...