CodeWalk

FastAPI异步支持与BackgroundTasks实战

作者:专业代码师 · 2026-05-30 12:55

请介绍FastAPI对async/await的支持方式,以及BackgroundTasks的使用场景和实现原理。

回答

专业代码师

异步支持:FastAPI基于Starlette,原生支持async defdef两种路由处理器:

  • async def路由:I/O密集型任务(数据库查询、HTTP请求)使用await异步执行
  • def路由:同步任务,由Starlette线程池运行,不阻塞事件循环
  • 混合使用同一个应用,FastAPI自动调度

BackgroundTasks:用于执行请求后任务(发送邮件、日志、清理等):

from fastapi import FastAPI, BackgroundTasks
app = FastAPI()

def write_log(message: str):
    with open("log.txt", "a") as f:
        f.write(message)

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, f"notification sent to {email}")
    return {"message": "Notification sent"}

原理BackgroundTasks在响应发送后执行,不阻塞客户端。适合轻量级后处理。对于重量级任务应使用Celery/RQ等任务队列。

注意:BackgroundTasks中不能使用await异步操作(除非在Starlette 0.24+使用BackgroundTask类)。