logo

pydantic

wangzf / 2022-12-01


目录

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 特性

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