Pokročilá validace vstupů a zpracování chyb

Nasazení AI do produkce s FastAPI

Matt Eckerle

Software and Data Engineering Leader

Proč potřebujeme pokročilé vstupy

 

  • API pro objednávky v restauraci
  • Proměnný počet položek

 

class Order(BaseModel):
    item1: str
    item2: str
    item3: str

Restaurace

Nasazení AI do produkce s FastAPI

Vnořené Pydantic modely

from pydantic import BaseModel

class Foo(BaseModel):
    count: int

class Bar(BaseModel):
    foo: Foo
>>> m = Bar(foo={'count': 4})
>>> print(m)
foo=Foo(count=4)
from pydantic import BaseModel
from typing import List

class OrderItem(BaseModel): name: str quantity: int
class RestaurantOrder(BaseModel): customer_name: str items: List[OrderItem]
Nasazení AI do produkce s FastAPI

Vlastní validátory modelu

from fastapi import FastAPI
from fastapi.exceptions import (
    RequestValidationError
)
from pydantic import (
    BaseModel,
    model_validator,
)

from typing import List class OrderItem(BaseModel): name: str quantity: int
class RestaurantOrder(BaseModel):
    customer_name: str
    items: List[OrderItem]

@model_validator(mode="after")
def validate_after(self): if len(self.items) == 0: raise RequestValidationError( "No items in order!" ) return self
{"detail":"No items in order!"}
Nasazení AI do produkce s FastAPI

Globální handlery výjimek

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse

app = FastAPI() @app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc): msg = "Input validation error. See the documentation: http://127.0.0.1:8000/docs" return PlainTextResponse(msg, status_code=422)
Input validation error. See the documentation: http://127.0.0.1:8000/docs
Nasazení AI do produkce s FastAPI

Pojďme si procvičit!

Nasazení AI do produkce s FastAPI

Preparing Video For Download...