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, kursun bir parçasıdır
Deploying AI into Production with FastAPI
Egzersiz talimatları
- Import the background task class from
fastapi. - Declare the
background_tasksparameter to handle the request as a task running in background. - Schedule the processing task of analyzing reviews' texts using the
process_reviewsfunction.
Uygulamalı etkileşimli egzersiz
Bu egzersizi bu örnek kodu tamamlayarak deneyin.
# 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"}