Zuletzt aktiv 9 months ago

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

timmy hat die Gist bearbeitet 9 months ago. Zu Änderung gehen

3 files changed, 34 insertions

dynamic_model_creation.py(Datei erstellt)

@@ -0,0 +1,10 @@
1 + from pydantic import create_model
2 +
3 + DynamicUser = create_model(
4 + "DynamicUser",
5 + username=(str, Field(..., min_length=3)),
6 + score=(int, Field(default=0, ge=0)),
7 + )
8 +
9 + user = DynamicUser(username="Alice", score=10)
10 + print(user.dict())

gistfile1.txt(Datei erstellt)

@@ -0,0 +1,13 @@
1 + from pydantic import BaseModel, Field, ValidationError
2 +
3 + class 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 + # 測試資料
9 + try:
10 + user = User(name="Tim", age=30, email="tim@example.com")
11 + print(user.dict()) # 轉換為字典
12 + except ValidationError as e:
13 + print(e)

pydantic_validation_example.py(Datei erstellt)

@@ -0,0 +1,11 @@
1 + from pydantic import BaseModel, ValidationError
2 +
3 + class Product(BaseModel):
4 + name: str
5 + price: float
6 +
7 + try:
8 + product = Product(name="Laptop", price="Free") # 錯誤:price 應為 float
9 + except ValidationError as e:
10 + print("驗證錯誤:")
11 + print(e)
Neuer Älter