BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Deploying AI into Production with FastAPI

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • 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.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# 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"}
Kodu Düzenle ve Çalıştır