开始使用免费开始使用

实现后台任务

您的情感分析 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"}
编辑并运行代码