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