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 엔드포인트 보호
- 구성 스키마 유효성 검사
- 데이터베이스 인터페이스