Zuletzt aktiv 9 months ago

pydantic 提供基於 Python 類別的數據驗證與解析功能,適用於 API 請求驗證、資料模型定義、設定管理 等場景。

Änderung 0be37238c654e3e05e5288db8f7739460af5f54a

dynamic_model_creation.py Originalformat
1from pydantic import create_model
2
3DynamicUser = create_model(
4 "DynamicUser",
5 username=(str, Field(..., min_length=3)),
6 score=(int, Field(default=0, ge=0)),
7)
8
9user = DynamicUser(username="Alice", score=10)
10print(user.dict())
11
gistfile1.txt Originalformat
1from pydantic import BaseModel, Field, ValidationError
2
3class User(BaseModel):
4 name: str = Field(..., title="使用者名稱", min_length=2)
5 age: int = Field(..., gt=0, le=150, description="年齡必須介於 1 到 150 之間")
6 email: str
7
8# 測試資料
9try:
10 user = User(name="Tim", age=30, email="tim@example.com")
11 print(user.dict()) # 轉換為字典
12except ValidationError as e:
13 print(e)
14
pydantic_validation_example.py Originalformat
1from pydantic import BaseModel, ValidationError
2
3class Product(BaseModel):
4 name: str
5 price: float
6
7try:
8 product = Product(name="Laptop", price="Free") # 錯誤:price 應為 float
9except ValidationError as e:
10 print("驗證錯誤:")
11 print(e)
12