Xác thực đầu vào nâng cao và xử lý lỗi

Triển khai AI vào môi trường sản xuất với FastAPI

Matt Eckerle

Software and Data Engineering Leader

Vì sao cần đầu vào nâng cao

 

  • API cho gọi món nhà hàng
  • Số lượng món linh hoạt

 

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

Một nhà hàng

Triển khai AI vào môi trường sản xuất với FastAPI

Mô hình lồng nhau trong Pydantic

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]
Triển khai AI vào môi trường sản xuất với FastAPI

Trình xác thực mô hình tùy chỉnh

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!"}
Triển khai AI vào môi trường sản xuất với FastAPI

Bộ xử lý ngoại lệ toàn cục

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
Triển khai AI vào môi trường sản xuất với FastAPI

Cùng luyện tập nào!

Triển khai AI vào môi trường sản xuất với FastAPI

Preparing Video For Download...