- 官方文档:
https://pydantic-docs.helpmanual.io/
- 这些组织都在用:
Jupyter notebook ; FastAPI ; Amazon Web Services ; Uber ; Microsoft
- 优势: 可以和IDE结合, 可以读取环境变量, 对环境变量做一些检查, 对一些用Python做自动化运维的人来说是福音,比其他的类型检查库要快,可以校验复杂的数据结构(validator),集成到FastAPI框架中写起来会很优雅, Django的DRF也有自己的序列化框架,Golang的Gin框架同样也是.FastAPI和Gin一样优雅, 很喜欢, 并且对扩展开放, 用户可以自定义校验规则
- 官方的复杂校验案例:
from pydantic import BaseModel, ValidationError, validator
class UserModel(BaseModel):
name: str
username: str
password1: str
password2: str
@validator('name')
def name_must_contain_space(cls, v):
if ' ' not in v:
raise ValueError('must contain a space')
return v.title()
@validator('password2')
def passwords_match(cls, v, values, **kwargs):
if 'password1' in values and v != values['password1']:
raise ValueError('passwords do not match')
return v
@validator('username')
def username_alphanumeric(cls, v):
assert v.isalpha(), 'must be alphanumeric'
return v
print(UserModel(name='samuel colvin', username='scolvin', password1='zxcvbn',
password2='zxcvbn'))
try:
UserModel(name='samuel', username='scolvin', password1='zxcvbn',
password2='zxcvbn2')
except ValidationError as e:
print(e)
"""
2 validation errors for UserModel
name
must contain a space (type=value_error)
password2
passwords do not match (type=value_error)
"""
from datetime import datetime
from pydantic.dataclasses import dataclass
@dataclass
class User:
id: int
name: str = 'John Doe'
signup_ts: datetime = None
user = User(id='42', signup_ts='2032-06-21T12:00')
print(user)
from typing import List
from datetime import datetime
from pydantic import BaseModel, ValidationError
class User(BaseModel):
id: int
name = "chr"
signUp_ts: datetime = None
friends: List[int] = []
data = {
"id": 123,
"signUp_ts": datetime.now(),
"friends": [1, 2, "a"]
}
try:
user = User(**data)
except ValidationError as e:
print(e.json())