IniziaInizia gratis

Implementing background tasks

Your sentiment analysis API is getting requests to process batch of hundreds of reviews at once. To handle this efficiently without making users wait, you'll implement background task processing so that requests are being processed after sending a response to the client.

Questo esercizio fa parte del corso

Deploying AI into Production with FastAPI

Visualizza il corso

Istruzioni dell'esercizio

  • Import the background task class from fastapi.
  • Declare the background_tasks parameter to handle the request as a task running in background.
  • Schedule the processing task of analyzing reviews' texts using the process_reviews function.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il 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"}
Modifica ed esegui il codice