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. 【LG5444】[APIO2019]奇怪装置

    [LG5444][APIO2019]奇怪装置 题面 洛谷 题目大意: 给定\(A,B\),对于\(\forall t\in \mathbb N\),有二元组\((x,y)=((t+\lfloor\fr ...

  2. Codeforces Round 563 (Div. 2) 题解

    自己开了场镜像玩. 前三题大水题.D有点意思.E完全不会.F被题意杀了……然而还是不会. 不过看过(且看懂)了官方题解,所以这里是六题题解齐全的. A 水题.给原序列排序,如果此时合法则直接输出,否则 ...

  3. ZROI 暑期高端峰会 A班 Day4 生成函数

    一般生成函数 很普及组,不讲了 生成函数是一种形式幂级数,也就是我们只关心系数,不关心未知数具体的值. 比如 \(\sum\limits_{i\ge 0}x^i=\frac{1}{1-x}\).虽然只 ...

  4. 应用JWT进行用户认证及Token的刷新

    本文将通过实际的例子来演示如何在ASP.NET Core中应用JWT进行用户认证以及Token的刷新方案(ASP.NET Core 系列目录) 一.什么是JWT? JWT(json web token ...

  5. Linux简介和各发行版介绍

    一.Linux 简介 Linux 内核最初只是由芬兰人李纳斯·托瓦兹(Linus Torvalds)在大学上学时出于个人爱好而编写的. Linux 是一套免费使用和自由传播的类 Unix 操作系统,是 ...

  6. window 运行spark报错

    Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties // :: ERROR Shell: F ...

  7. shell脚本监控httpd服务80端口状态

    监控httpd服务端口状态,根据端口判断服务器是否启动,如果没有启动则脚本自动拉起服务,如果服务正在运行则退出脚本程序:如果换成别的服务端口也可以,但是脚本程序需要做调整. #!/bin/bash # ...

  8. 解决wireshark抓包校验和和分片显示异常

    问题描述: 在使用wireshark抓取报文时,发现从10.81.2.92发过来的报文绝大部分标记为异常报文(开启IPv4和TCP checksum) 分析如下报文,发现http报文(即tcp pay ...

  9. 【剑指offer】构建乘积数组

    题目描述 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1].不 ...

  10. [转帖]ps 命令详解

    ps 命令详解 https://www.jianshu.com/p/cba22cce2f97 ps 概述 Linux中的ps命令是Process Status的缩写.ps命令用来列出系统中当前运行的那 ...