FastAPI로 AI 프로덕션 배포하기
Matt Eckerle
Software and Data Engineering Leader

여러 요청을 동시에 처리할 수 있습니다

@app.post("/analyze")
def analyze_sync(comment: Comment):
result = sentiment_model(comment.text)
return {"sentiment": result}
import asyncio
@app.post("/analyze")
async def analyze_async(comment: Comment):
result = await asyncio.to_thread(
sentiment_model, comment.text
)
return {"sentiment": result}
from fastapi import BackgroundTasks
from typing import List
@app.post("/analyze_batch")
async def analyze_batch(
comments: Comments,
background_tasks: BackgroundTasks
):
async def process_comments(texts: List[str]):
for text in texts:
result = await asyncio.to_thread(
sentiment_model, text)
background_tasks.add_task(process_comments,
comments.texts)
return {"message": "Processing started"}
BackgroundTasks는 댓글 처리 큐를 관리합니다.
background_tasks는 응답 후 처리를 담당합니다.
add_task는 process_comments를 비동기로 예약합니다.@app.post("/analyze_comment")
async def analyze_comment(comment: Comment):
try:
sentiment_model = SentimentAnalyzer()
result = await asyncio.wait_for(
sentiment_model(comment.text),
timeout=5.0
)
return {"sentiment": result["label"]}
except asyncio.TimeoutError:
raise HTTPException(
status_code=408,
detail="Analysis timed out"
)
except Exception:
raise HTTPException(
status_code=500,
detail="Analysis failed"
)
FastAPI로 AI 프로덕션 배포하기