Django之DRF源码分析(二)---数据校验部分
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源码分析(二)---数据校验部分的更多相关文章
- Django搭建及源码分析(二)
上节针对linux最小系统,如何安装Django,以及配置简单的Django环境进行了说明. 本节从由Django生成的manage.py开始,分析Django源码.python版本2.6,Djang ...
- Django之DRF源码分析(四)---频率认证组件
核心源码 def check_throttles(self, request): """ Check if request should be throttled. Ra ...
- Django与drf 源码视图解析
0902自我总结 Django 与drf 源码视图解析 一.原生Django CBV 源码分析:View """ 1)as_view()是入口,得到view函数地址 2) ...
- Django搭建及源码分析(三)---+uWSGI+nginx
每个框架或者应用都是为了解决某些问题才出现旦生的,没有一个事物是可以解决所有问题的.如果觉得某个框架或者应用使用很不方便,那么很有可能就是你没有将其使用到正确的地方,没有按开发者的设计初衷来使用它,当 ...
- Fresco 源码分析(二) Fresco客户端与服务端交互(1) 解决遗留的Q1问题
4.2 Fresco客户端与服务端的交互(一) 解决Q1问题 从这篇博客开始,我们开始讨论客户端与服务端是如何交互的,这个交互的入口,我们从Q1问题入手(博客按照这样的问题入手,是因为当时我也是从这里 ...
- HDFS源码分析之数据块及副本状态BlockUCState、ReplicaState
关于数据块.副本的介绍,请参考文章<HDFS源码分析之数据块Block.副本Replica>. 一.数据块状态BlockUCState 数据块状态用枚举类BlockUCState来表示,代 ...
- 十、Spring之BeanFactory源码分析(二)
Spring之BeanFactory源码分析(二) 前言 在前面我们简单的分析了BeanFactory的结构,ListableBeanFactory,HierarchicalBeanFactory,A ...
- Vue源码分析(二) : Vue实例挂载
Vue源码分析(二) : Vue实例挂载 author: @TiffanysBear 实例挂载主要是 $mount 方法的实现,在 src/platforms/web/entry-runtime-wi ...
- 框架-springmvc源码分析(二)
框架-springmvc源码分析(二) 参考: http://www.cnblogs.com/leftthen/p/5207787.html http://www.cnblogs.com/leftth ...
随机推荐
- 绘制matplotlib 饼状图
参考:https://blog.csdn.net/ScarlettYellow/article/details/80458797 (2)2016年就业人员在三次产业中分布的饼状图. def swap( ...
- HTML基础知识---文本编辑练习
飘柔兰花去油洗发水液露去屑止痒控油 阿道夫净屑舒爽清洁头皮去屑洗发水520ml ...
- windows下SVN使用 Add指令、Undo Add指令
前几天,使用SVN的Add指令添加了一个文件,后不使用直接删除了,每次提交都存在,解决后记录方法,希望帮到大家,此外如果大家有好的方法,希望可以回复. 问题:使用Add添加文件后直接删除了文件,每次提 ...
- Scopus数据库简介
ScienceDirect数据库1. Elsevier简介荷兰Elsevier 是全球最大的科学文献出版发行商,已有180多年的历史.其产品涵盖科学.技术和医学等各个领域,包括1800多种学术期刊(大 ...
- Proxy代理对象是如何调用invoke()方法的.
直奔主题,不说废话.先看java使用Proxy创建代理对象的代码. //一个开发者接口public interface Developer { String code(); void debug(); ...
- 记一次网络故障——pod间无法通信
一.背景 集群是二进制部署 部署完成后一起正常,各种资源对象均可正常创建. 部署应用后发现无法跨节点通信,且pod的ip都是172.17.0.0段的 二.排查过程层 查看节点路由,发现docker0网 ...
- recttransform
转载自https://www.jianshu.com/p/4592bf809c8b 1.Anchor:子物体和父物体联系的桥梁,Anchors是由两个点确定的,他们就是AnchorMin以及Ancho ...
- 彻底解决springboot修改页面和代码会自动重启
3.application.yml配置 spring.devtools.restart.enabled=falsespring.thymeleaf.cache=false 1.解决thymeleaf修 ...
- Java 中将字符串数组转换为字符串
Java 中将字符串数组转换为字符串 import java.util.Arrays; import java.util.HashSet; import java.util.Set; public c ...
- lower_bound()和upper_bound()
lower_bound()和upper_bound() 是方便的在有序数组中二分查找的函数,并且在STL其他数据结构中也提供该方法(如map和set). 但是两函数并不是二分查找"小于&qu ...