Implementare task in background
La tua API di sentiment analysis riceve richieste per elaborare in blocco centinaia di recensioni alla volta. Per gestirlo in modo efficiente senza far aspettare gli utenti, implementerai l'esecuzione di task in background così che le richieste vengano elaborate dopo l'invio della risposta al client.
Questo esercizio fa parte del corso
Deployment di AI in produzione con FastAPI
Istruzioni dell'esercizio
- Importa la classe per i task in background da
fastapi. - Dichiara il parametro
background_tasksper gestire la richiesta come un task che gira in background. - Pianifica il task di elaborazione per analizzare i testi delle recensioni usando la funzione
process_reviews.
esercizio interattivo pratico
Prova questo esercizio completando questo codice di esempio.
# Import the background task class
from fastapi import ____
# Create a background task dependency
@app.post("/analyze_batch")
async def analyze_batch(
reviews: Reviews,
background_tasks: ____
):
async def process_reviews(texts: List[str]):
for text in texts:
result = await asyncio.to_thread(sentiment_model, text)
print(f"Processed: {result[0]['label']}")
# Add the task of analysing reviews' texts to the background
background_tasks.____(process_reviews, reviews.texts)
return {"message": "Processing started"}