Pydantic 驗證
類型強制和模型驗證。
概述
Pydantic 允許 Python 資料類別自動將根本上無類型的網路配置轉變為類型化表示。
這使用穩健的類型約束來保護系統狀態。
程式碼和執行輸出
聲明用於驗證有效負載的嚴格模式使用者模型。
models.py
在編輯器中嘗試from pydantic import BaseModel, EmailStr, Field
from typing import List, Optional
import json
class User(BaseModel):
id: int
name: str = Field(min_length=2)
email: EmailStr
tags: List[str] = []
is_active: bool = True
# Simulating an API response with mixed types
incoming_data = {
"id": "123", # string gets coerced to int
"name": "Alice",
"email": "alice@example.com",
"tags": ("python", "developer") # tuple gets coerced to list
}
# Validate and instantiate
user = User(**incoming_data)
print("--- Validated Pydantic Model ---")
print(repr(user))
print("\n--- Exported to JSON ---")
print(user.model_dump_json(indent=2))端子輸出
--- Validated Pydantic Model ---
User(id=123, name='Alice', email='alice@example.com', tags=['python', 'developer'], is_active=True)
--- Exported to JSON ---
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"tags": [
"python",
"developer"
],
"is_active": true
}逐步實施
- API endpoint protection
- Config schema validation
- Database interfacing