pydantic
wangzf
/
2022-12-01
目录
- Data validation and settings management using python type annotations.
- pydantic enforces type hints at runtime, and provides user friendly errors when data *s invalid.
- Define how data should be in pure, canonical python; validate it with pydantic.
pydantic 示例
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
from pydantic import ValidationError
class User(BaseModel):
id: int
name = "John Doe"
singnup_ts: Optional[datetime] = None
friends: List[int] = []
external_data = {
"id": "123",
"singnup_ts": "2019-06-01 12:22",
"friends": [1, 2, "3"],
}
user = User(**external_data)
print(user.id)
print(repr(user.singnup_ts))
print(user.friends)
print(user.dict())
try:
User(signup_ts = "broken", friends = [1, 2, "not number"])
except ValidationError as e:
print(e.json())
pydantic 特性
- 与 IDE/linter/brain 配合的很好
- Pydantic 的 BaseSettings 类允许在 验证此请求数据、加载系统设置中使用
- 速度快
- 能够验证复杂结构
- 可扩展
- 数据类集成
pydantic 安装
pydantic 依赖库
pip 安装
$ pip install pydantic
$ pip install "pydantic[email]"
$ pip install "pydantic[dotenv]"
$ pip install "pydantic[email,dotenv]"
$ pip install email-validation
$ pip install .
conda 安装
$ codna install pydantic -c conda-forge
测试安装
import pydantic
print("compiled", pydantic.compiled)
pydantic 使用
Models