简介

pydantic是一个基于type hint 的类型检查库

使用

Model

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from typing import Optional
from datetime import datetime

from pydantic import BaseModel, Field

class User(BaseModel):
    id:int
    name:str = "PPD"
    age: int = None
    hometown: Optional[str]                 # 等同于 hometown: Optional[str] = None
    email: Optional[str] = Field(...)    # 支持None,但必填字段
    dt: datetime = Field(default_factory=datetime.now) # 动态值,实例化的时候确定
user = User(id=1, age=3, email="hello@world.com")

print(user.dict()) # dict
print(user.json()) # json serialized dict
print(user.__fields_set__) # set of names of fields: {'id', 'age', email'}
  • field order: 父类的字段排在前面, 有类型申明的排在前面,其他按声明顺序来

Modle Config

1
2
3
4
5
6
7
from pydantic import BaseModel
class Model(BaseMel):
    a:int
    b: str
    
    class Config:
        allow_mutation = False  # instance can not change when it is set

Field Types

除了一些python标准类型,pydantic定义了一些约束类型,提供限制str的长度,数字的大小,列表的长度

1
2
3
class Model(BaseModel):
    short_str: constr(min_length=2,max_length=10)
    unit_interval: confloat(ge=0,le=1)

Validators

提供validator装饰器对字段级别进行验证

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class UserModel(BaseModel):
    name: str
    square_numbers: List[int] = []
    cube_numbers: List[int] = []
    
    @validator('name')
    def name_must_contain_space(cls, v):
        if ' ' not in v:
            raise ValueError('must contain a space')
        return v.title()
    
    @validator('cube_numbers', 'square_numbers')
    def split_str(cls, v):
        if isinstance(v, str):
            return v.split('|')
        return v
    
    @validator('cube_numbers', 'square_numbers')
    def check_sum(cls, v):
        if sum(v) > 42:
            raise ValueError('sum of numbers greater than 42')
        return v
        
    @validator('square_numbers', each_item=True)
    def check_squares(cls, v):
        assert v ** 0.5 % 1 == 0, f'{v} is not a square number'
        return v

Exporting models

model.dict()

配置选项

  • include: 包含的字段
  • exclude: 不包含的字段
  • exclude_unset: 不包含未设置的字段
  • exclude_defaults: 不包含未和默认值相同的字段
  • exclude_none: 不包含None的字段

model.json()

调用.dict()然后序列化

model.copy()

Settings management

设置Config,自动从环境变量中或.env文件中读取

  • 优先级

    • 显示设置
    • environment
    • .env file
    • default value