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 ...
随机推荐
- ZROI 暑期高端峰会 A班 Day3 字符串
FBI Warning:本文含有大量人类的本质之一 后缀树 反正后缀树就是反串的后缀自动机的 Parent 树,就不管了. 然而 SAM 也忘了 好的假装自己会吧--dls 后缀自动机 大概记得,不管 ...
- nginx 动静分离之 tomcat
配置文件示例 server { listen ; server_name www.xxx.com; location ~* "\.(jpg|png|jepg|js|css|xml|bmp|s ...
- 【cf比赛记录】Educational Codeforces Round 78 (Rated for Div. 2)
比赛传送门 A. Shuffle Hashing 题意:加密字符串.可以把字符串的字母打乱后再从前面以及后面接上字符串.问加密后的字符串是否符合加密规则. 题解:字符串的长度很短,直接暴力搜索所有情况 ...
- 使用 udev 进行动态内核设备管理(转自suse文档)
第 12 章使用 udev 进行动态内核设备管理¶ 目录 12.1. /dev 目录 12.2. 内核 uevents 和 udev 12.3. 驱动程序.内核模块和设备 12.4. 引导和启动设备设 ...
- 2018-2019-2 网络对抗技术 20165230 Exp9 :Web安全基础
目录 实验目的 实验内容 Webgoat前期准备 出现的问题 (一)SQL注入攻击 命令注入:Command Injection 数字型注入:Numeric SQL Injection 日志欺骗:Lo ...
- Django单元测试总结
title: Django单元测试总结 date: 2019/6/18 17:50:00 body: [article] description: " 在本文中,笔者大致对Django单元 ...
- leetcode 1110. 删点成林
题目描述: 给出二叉树的根节点 root,树上每个节点都有一个不同的值. 如果节点值在 to_delete 中出现,我们就把该节点从树上删去,最后得到一个森林(一些不相交的树构成的集合). 返回森林中 ...
- kali 触摸板手势之fusuma
1.执行如下命令进行安装 *fusuma 需要在ruby环境下运行,若计算机不支持ruby,则先执行:apt-get install ruby apt-get update apt-get insta ...
- this指北 (一篇读懂)
this 关键字 涵义 this关键字是一个非常重要的语法点.毫不夸张地说,不理解它的含义,大部分开发任务都无法完成. 前一章已经提到,this可以用在构造函数之中,表示实例对象.除此之外,this还 ...
- python安装 hanlp +使用 坑坑坑。。。填填填。。。
刚开始用都不知道要怎么安装,包括什么文件.百度了下发现正常安装就可以用,不用下多余的东西,但是但是但是但是但是但是但是但是 用pycharm安装不行,pip安装不行,也是见鬼了. 解决方法: 1.手动 ...