백그라운드 작업 구현하기
감성 분석 API에 수백 개의 리뷰를 한 번에 처리하는 배치 요청이 들어오고 있습니다. 사용자가 기다리지 않도록 효율적으로 처리하기 위해, 클라이언트에 응답을 먼저 보낸 후 요청을 백그라운드에서 처리하는 백그라운드 작업을 구현해 보겠습니다.
이 연습은 강의의 일부입니다
FastAPI로 AI 프로덕션 배포하기
연습 안내
- 백그라운드 작업 클래스를
fastapi에서 import하세요. - 요청을 백그라운드에서 실행되는 작업으로 처리할 수 있도록
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"}