教程

features 功能特点

  • 数据验证和设置工具
  • 通过 python annotations (typing) 实现
  • 在 runtime 时期强制执行 typing(type hint)
  • 类型不一致,给出错误提示

    • 异常: pydantic.ValidationError

      • 作用:记录所有的字段错误情况

优势

  • IDE, linter 友好

    • 类型检查,自动补全
  • 可以用于验证数据,也可以用户系统设置的加载
  • 速度快,底层使用库 cython 编译
  • 支持嵌套 model 验证(复杂结构)
  • 可扩展

    • 允许自定义数据类型
  • 与 dataclass 集成

pydantic 和 sqlalchemy model 互转

参考:

Field

要求必填 required

使用 ... 设置

1
2
3
4
from pydantic import BaseModel, Field

class MyModel(BaseModel):
    required_field: str = Field(..., description="This field is required")