扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
发现1000+提升效率与开发的AI工具和实用程序:https://tools.cmdragon.cn/
通过 FastAPI 的 BackgroundTasks 类型,我们可以将非即时性操作(如发送邮件、日志记录等)从主请求处理流程中分离。系统架构原理如下:
请求处理流程:
这种机制的优势在于:
使用 pydantic2.5.2 和 fastapi0.104.0 的示例:
from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel
app = FastAPI()
# 定义数据模型
class UserRegistration(BaseModel):
username: str
email: str
# 后台任务函数
def send_welcome_email(email: str):
# 模拟邮件发送(实际需替换真实SMTP配置)
print(f"Sending welcome email to {email}")
# 路由处理
@app.post("/register")
async def create_user(
user: UserRegistration,
background_tasks: BackgroundTasks
):
# 添加后台任务
background_tasks.add_task(send_welcome_email, user.email)
return {"message": "Registration successful"}
关键实现要素:
结合依赖注入系统实现复用:
from typing import Annotated
from fastapi import Depends
def get_notification_service():
# 模拟通知服务初始化
return NotificationService()
@app.post("/order")
async def create_order(
background_tasks: BackgroundTasks,
notify_service: Annotated[NotificationService, Depends(get_notification_service)]
):
background_tasks.add_task(
notify_service.send_order_confirmation,
order_id=123
)
同步与异步任务混合示例:
async def async_task_1():
await asyncio.sleep(1)
def sync_task_2():
time.sleep(2)
@app.get("/complex-task")
def complex_operation(background_tasks: BackgroundTasks):
background_tasks.add_task(async_task_1)
background_tasks.add_task(sync_task_2)
使用 pytest7.4.0 和 httpx0.25.0:
from fastapi.testclient import TestClient
def test_background_task():
client = TestClient(app)
with mock.patch("module.send_welcome_email") as mock_task:
response = client.post("/register", json={
"username": "testuser",
"email": "test@example.com"
})
assert response.status_code == 200
mock_task.assert_called_once_with("test@example.com")
Q1:当需要确保后台任务在应用关闭前完成时,应该如何处理?
A:使用 lifespan 事件监听,在 shutdown 阶段等待任务完成。正确做法是注册应用生命周期钩子,在关闭时调用 BackgroundTasks 的等待方法。
Q2:后台任务中出现异常会导致主请求失败吗?
A:不会。后台任务异常会记录到日志但不会影响主请求响应,需要通过自定义错误处理中间件捕获。
报错现象:后台任务未执行
原因分析:
解决方案:
余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
,阅读完整的文章:如何在FastAPI中让后台任务既高效又不会让你的应用崩溃?
参与评论
手机查看
返回顶部