Procesare asincronă

Deployment AI în producție cu FastAPI

Matt Eckerle

Software and Data Engineering Leader

Ce este procesarea asincronă

O persoană care servește o băutură unui client la masă

 

Permite gestionarea simultană a mai multor cereri

Deployment AI în producție cu FastAPI

Cereri sincrone vs. asincrone

Grafic comparând timpii de procesare pentru cereri sincrone și asincrone

Deployment AI în producție cu FastAPI

Conversia endpoint-urilor sincrone în asincrone

 

@app.post("/analyze")
def analyze_sync(comment: Comment):
    result = sentiment_model(comment.text)
    return {"sentiment": result}

 

import asyncio

@app.post("/analyze")
async def analyze_async(comment: Comment):
    result = await asyncio.to_thread(
        sentiment_model, comment.text
    )
    return {"sentiment": result}
Deployment AI în producție cu FastAPI

Implementarea sarcinilor de fundal

from fastapi import BackgroundTasks
from typing import List
@app.post("/analyze_batch")
async def analyze_batch(
    comments: Comments,
    background_tasks: BackgroundTasks
):
    async def process_comments(texts: List[str]):
        for text in texts:
            result = await asyncio.to_thread(
              sentiment_model, text)
    background_tasks.add_task(process_comments, 
                              comments.texts)
    return {"message": "Processing started"}
  • BackgroundTasks gestionează coada de procesare a comentariilor.

 

  • background_tasks procesează datele după trimiterea răspunsului.

 

  • add_task planifică process_comments asincron.
Deployment AI în producție cu FastAPI

Adăugarea gestionării erorilor

@app.post("/analyze_comment")
async def analyze_comment(comment: Comment):
    try:
        sentiment_model = SentimentAnalyzer()
        result = await asyncio.wait_for(
            sentiment_model(comment.text),
            timeout=5.0
        )
        return {"sentiment": result["label"]}
Deployment AI în producție cu FastAPI

Adăugarea gestionării erorilor

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Analysis timed out"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Analysis failed"
        )
Deployment AI în producție cu FastAPI

Să exersăm!

Deployment AI în producție cu FastAPI

Preparing Video For Download...