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.
Deze oefening maakt deel uit van de cursus
Deploying AI into Production with FastAPI
Oefeninstructies
- 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.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# 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"}