Fastapi之BackgroundTasks

如何在 FastAPI 中使用 BackgroundTasks 来异步执行后台任务

python 复制代码
import asyncio
import logging
import time

from fastapi import FastAPI, BackgroundTasks

# 配置日志记录级别
logging.basicConfig(level=logging.INFO)

# 初始化FastAPI应用
app = FastAPI(routes=None)

# 初始化任务状态字典
task_status = {}

def send_mail(n, task_id):
    """
    模拟发送邮件的任务函数。
    
    参数:
    - n: 邮件发送预计耗时的秒数。
    - task_id: 任务的唯一标识符。
    """
    logging.info(f"开始发送邮件,预计耗时 {n} 秒,任务ID: {task_id}")
    time.sleep(n)  # 模拟邮件发送耗时
    logging.info(f"邮件发送完成,耗时 {n} 秒,任务ID: {task_id}")
    task_status[task_id] = "completed"  # 更新任务状态为完成

@app.api_route(path="/index", methods=["GET", "POST"])
async def index(tasks: BackgroundTasks):
    """
    主要的API路由处理函数。
    
    参数:
    - tasks: 用于在后台执行任务的任务管理器。
    
    返回:
    - 一个包含任务ID的字典。
    """
    task_id = str(int(time.time() * 1000))  # 生成一个唯一的任务ID
    task_status[task_id] = "running"  # 更新任务状态为运行中
    tasks.add_task(send_mail, 10, task_id)  # 将邮件发送任务添加到后台任务中
    print(id(asyncio.get_event_loop()))  # 打印当前事件循环的ID
    return {"index": "index", "task_id": task_id}

@app.get("/status/{task_id}")
async def get_task_status(task_id: str):
    """
    获取任务状态的API路由处理函数。
    
    参数:
    - task_id: 任务的唯一标识符。
    
    返回:
    - 一个包含任务ID和状态的字典。
    """
    status = task_status.get(task_id, "not found")  # 获取任务状态,如果不存在则返回"not found"
    return {"task_id": task_id, "status": status}

if __name__ == "__main__":
    import uvicorn
    import os
    
    # 获取应用模型名称,用于uvicorn运行
    app_model_name = os.path.basename(__file__).replace(".py", "")
    print(app_model_name)
    
    # 使用uvicorn运行FastAPI应用
    uvicorn.run(f"{app_model_name}:app", host='0.0.0.0', reload=True)
相关推荐
前端付豪3 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽3 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战3 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋9 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构