การสร้าง Background Task
API วิเคราะห์ความรู้สึกของคุณได้รับคำขอให้ประมวลผลรีวิวเป็นชุดครั้งละหลายร้อยรายการ เพื่อรับมือกับสิ่งนี้ได้อย่างมีประสิทธิภาพโดยไม่ทำให้ผู้ใช้ต้องรอนาน คุณจะนำการประมวลผลแบบ background task มาใช้ เพื่อให้คำขอถูกประมวลผลหลังจากส่งการตอบกลับไปยัง client แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การ Deploy AI สู่ Production ด้วย FastAPI
คำแนะนำการฝึกหัด
- Import คลาส background task จาก
fastapi - ประกาศพารามิเตอร์
background_tasksเพื่อจัดการคำขอในฐานะ task ที่ทำงานอยู่เบื้องหลัง - กำหนดเวลาสำหรับ task การประมวลผลข้อความรีวิวโดยใช้ฟังก์ชัน
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"}