實作背景任務
你的情緒分析 API 會一次收到數百則評論要批次處理。為了有效處理且不讓使用者久候,你將實作背景任務處理,讓伺服器在回應用戶端之後,持續在背景處理請求。
本練習屬於課程
使用 FastAPI 將 AI 佈署到生產環境
練習說明
- 從
fastapi匯入背景任務類別。 - 宣告
background_tasks參數,將請求作為在背景執行的任務處理。 - 使用
process_reviews函式,排程處理評論文字的分析任務。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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"}