Pydantic — 强大的数据校验工具,比DRF的校验器还快12倍

2022-01-17 12:51

本文目录

Pydantic 是一个使用Python类型注解进行数据验证和管理的模块。安装方法非常简单,打开终端输入:

  1. pip install pydantic

它类似于 Django DRF 序列化器的数据校验功能,不同的是,Django里的序列化器的Field是有限制的,如果你想要使用自己的Field还需要继承并重写它的基类:

  1. # Django 序列化器
  2. class Book(models.Model):
  3. id = models.AutoField(primary_key=True)
  4. name = models.CharField(max_length=32)
  5. price = models.DecimalField(max_digits=5, decimal_places=2)
  6. author = models.CharField(max_length=32)
  7. publish = models.CharField(max_length=32)

而 Pydantic 基于Python3.7以上的类型注解特性,实现了可以对任何类做数据校验的功能:

  1. # Pydantic 数据校验功能
  2. from datetime import datetime
  3. from typing import List, Optional
  4. from pydantic import BaseModel
  5. class User(BaseModel):
  6. id: int
  7. name = 'John Doe'
  8. signup_ts: Optional[datetime] = None
  9. friends: List[int] = []
  10. external_data = {
  11. 'id': '123',
  12. 'signup_ts': '2019-06-01 12:22',
  13. 'friends': [1, 2, '3'],
  14. }
  15. user = User(**external_data)
  16. print(user.id)
  17. print(type(user.id))
  18. #> 123
  19. #> <class 'int'>
  20. print(repr(user.signup_ts))
  21. #> datetime.datetime(2019, 6, 1, 12, 22)
  22. print(user.friends)
  23. #> [1, 2, 3]
  24. print(user.dict())
  25. """
  26. {
  27. 'id': 123,
  28. 'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
  29. 'friends': [1, 2, 3],
  30. 'name': 'John Doe',
  31. }
  32. """

从上面的基本使用可以看到,它甚至能自动帮你做数据类型的转换,比如代码中的 user.id, 在字典中是字符串,但经过Pydantic校验器后,它自动变成了int型,因为User类里的注解就是int型。

当我们的数据和定义的注解类型不一致时会报这样的Error:

  1. from datetime import datetime
  2. from typing import List, Optional
  3. from pydantic import BaseModel
  4. class User(BaseModel):
  5. id: int
  6. name = 'John Doe'
  7. signup_ts: Optional[datetime] = None
  8. friends: List[int] = []
  9. external_data = {
  10. 'id': '123',
  11. 'signup_ts': '2019-06-01 12:222',
  12. 'friends': [1, 2, '3'],
  13. }
  14. user = User(**external_data)
  15. """
  16. Traceback (most recent call last):
  17. File "1.py", line 18, in <module>
  18. user = User(**external_data)
  19. File "pydantic\main.py", line 331, in pydantic.main.BaseModel.__init__
  20. pydantic.error_wrappers.ValidationError: 1 validation error for User
  21. signup_ts
  22. invalid datetime format (type=value_error.datetime)
  23. """

即 “invalid datetime format”, 因为我传入的 signup_ts 不是标准的时间格式(多了个2)。

1.Pydantic 模型数据导出

通过Pydantic模型中自带的 json 属性方法,能让经过校验后的数据一行命令直接转成 json 字符串,如前文中的user对象:

  1. print(user.dict()) # 转为字典
  2. """
  3. {
  4. 'id': 123,
  5. 'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
  6. 'friends': [1, 2, 3],
  7. 'name': 'John Doe',
  8. }
  9. """
  10. print(user.json()) # 转为json
  11. """
  12. {"id": 123, "signup_ts": "2019-06-01T12:22:00", "friends": [1, 2, 3], "name": "John Doe"}
  13. """

非常方便。它还支持将整个数据结构导出为 schema json,它能完整地描述整个对象的数据结构类型:

  1. print(user.schema_json(indent=2))
  2. """
  3. {
  4. "title": "User",
  5. "type": "object",
  6. "properties": {
  7. "id": {
  8. "title": "Id",
  9. "type": "integer"
  10. },
  11. "signup_ts": {
  12. "title": "Signup Ts",
  13. "type": "string",
  14. "format": "date-time"
  15. },
  16. "friends": {
  17. "title": "Friends",
  18. "default": [],
  19. "type": "array",
  20. "items": {
  21. "type": "integer"
  22. }
  23. },
  24. "name": {
  25. "title": "Name",
  26. "default": "John Doe",
  27. "type": "string"
  28. }
  29. },
  30. "required": [
  31. "id"
  32. ]
  33. }
  34. """

2.数据导入

除了直接定义数据校验模型,它还能通过ORM、字符串、文件导入到数据校验模型:

比如字符串(raw):

  1. from datetime import datetime
  2. from pydantic import BaseModel
  3. class User(BaseModel):
  4. id: int
  5. name = 'John Doe'
  6. signup_ts: datetime = None
  7. m = User.parse_raw('{"id": 123, "name": "James"}')
  8. print(m)
  9. #> id=123 signup_ts=None name='James'

此外,它能直接将ORM的对象输入,转为Pydantic的对象,比如从Sqlalchemy ORM:

  1. from typing import List
  2. from sqlalchemy import Column, Integer, String
  3. from sqlalchemy.dialects.postgresql import ARRAY
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from pydantic import BaseModel, constr
  6. Base = declarative_base()
  7. class CompanyOrm(Base):
  8. __tablename__ = 'companies'
  9. id = Column(Integer, primary_key=True, nullable=False)
  10. public_key = Column(String(20), index=True, nullable=False, unique=True)
  11. name = Column(String(63), unique=True)
  12. domains = Column(ARRAY(String(255)))
  13. class CompanyModel(BaseModel):
  14. id: int
  15. public_key: constr(max_length=20)
  16. name: constr(max_length=63)
  17. domains: List[constr(max_length=255)]
  18. class Config:
  19. orm_mode = True
  20. co_orm = CompanyOrm(
  21. id=123,
  22. public_key='foobar',
  23. name='Testing',
  24. domains=['example.com', 'foobar.com'],
  25. )
  26. print(co_orm)
  27. #> <models_orm_mode.CompanyOrm object at 0x7f0bdac44850>
  28. co_model = CompanyModel.from_orm(co_orm)
  29. print(co_model)
  30. #> id=123 public_key='foobar' name='Testing' domains=['example.com',
  31. #> 'foobar.com']

从Json文件导入:

  1. from datetime import datetime
  2. from pathlib import Path
  3. from pydantic import BaseModel
  4. class User(BaseModel):
  5. id: int
  6. name = 'John Doe'
  7. signup_ts: datetime = None
  8. path = Path('data.json')
  9. path.write_text('{"id": 123, "name": "James"}')
  10. m = User.parse_file(path)
  11. print(m)

从pickle导入:

  1. import pickle
  2. from datetime import datetime
  3. from pydantic import BaseModel
  4. pickle_data = pickle.dumps({
  5. 'id': 123,
  6. 'name': 'James',
  7. 'signup_ts': datetime(2017, 7, 14)
  8. })
  9. m = User.parse_raw(
  10. pickle_data, content_type='application/pickle', allow_pickle=True
  11. )
  12. print(m)
  13. #> id=123 signup_ts=datetime.datetime(2017, 7, 14, 0, 0) name='James'

3.自定义数据校验

你还能给它增加 validator 装饰器,增加你需要的校验逻辑:

  1. from pydantic import BaseModel, ValidationError, validator
  2. class UserModel(BaseModel):
  3. name: str
  4. username: str
  5. password1: str
  6. password2: str
  7. @validator('name')
  8. def name_must_contain_space(cls, v):
  9. if ' ' not in v:
  10. raise ValueError('must contain a space')
  11. return v.title()
  12. @validator('password2')
  13. def passwords_match(cls, v, values, **kwargs):
  14. if 'password1' in values and v != values['password1']:
  15. raise ValueError('passwords do not match')
  16. return v
  17. @validator('username')
  18. def username_alphanumeric(cls, v):
  19. assert v.isalnum(), 'must be alphanumeric'
  20. return v

上面,我们增加了三种自定义校验逻辑:

1.name 必须带有空格

2.password2 必须和 password1 相同

3.username 必须为字母

让我们试试这三个校验是否成功实现:

  1. user = UserModel(
  2. name='samuel colvin',
  3. username='scolvin',
  4. password1='zxcvbn',
  5. password2='zxcvbn',
  6. )
  7. print(user)
  8. #> name='Samuel Colvin' username='scolvin' password1='zxcvbn' password2='zxcvbn'
  9. try:
  10. UserModel(
  11. name='samuel',
  12. username='scolvin',
  13. password1='zxcvbn',
  14. password2='zxcvbn2',
  15. )
  16. except ValidationError as e:
  17. print(e)
  18. """
  19. 2 validation errors for UserModel
  20. name
  21. must contain a space (type=value_error)
  22. password2
  23. passwords do not match (type=value_error)
  24. """

可以看到,第一个UserModel里的数据完全没有问题,通过校验。

第二个UserModel里的数据,由于name存在空格,password2和password1不一致,无法通过校验。

4.性能表现

这是最令我惊讶的部分,Pydantic 比 Django-rest-framework 还快了12.3倍:

Package Version Relative Performance Mean validation time
pydantic 1.7.3 93.7μs
attrs + cattrs 20.3.0 1.5x slower 143.6μs
valideer 0.4.2 1.9x slower 175.9μs
marshmallow 3.10.0 2.4x slower 227.6μs
voluptuous 0.12.1 2.7x slower 257.5μs
trafaret 2.1.0 3.2x slower 296.7μs
schematics 2.1.0 10.2x slower 955.5μs
django-rest-framework 3.12.2 12.3x slower 1148.4μs
cerberus 1.3.2 25.9x slower 2427.6μs

而且他们的所有基准测试代码都是开源的,你可以在下面这个Github链接找到:

https://github.com/samuelcolvin/pydantic/tree/master/benchmarks