Pydantische Validierung

Typzwang und Modellvalidierung.

Versuchen Sie es im Editor

Übersicht

Mit Pydantic können Python-Datenklassen grundsätzlich untypisierte Netzwerkkonfigurationen automatisch in typisierte Darstellungen umwandeln.

Dies schützt den Systemstatus mithilfe robuster Typbeschränkungen.

Code- und Ausführungsausgabe

Deklariert ein striktes Schema-Benutzermodell für Validierungsnutzlasten.

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))
Terminal-Ausgabe
--- 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
}

Schrittweise Umsetzung

  • API-Endpunktschutz
  • Validierung des Konfigurationsschemas
  • Datenbankanbindung

Häufig gestellte Fragen

Verwandte Themen