【Python笔记-FastAPI】后台任务+WebSocket监控进度

目录

一、代码示例

二、执行说明

[(一) 调用任务执行接口](#(一) 调用任务执行接口)

[(二) 监控任务进度](#(二) 监控任务进度)


实现功能:

  1. 注册后台任务(如:邮件发送、文件处理等异步场景,不影响接口返回)
  2. 监控后台任务执行进度(进度条功能)
  3. 支持根据任务ID查询对应任务进度

一、代码示例

python 复制代码
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import random
import asyncio

from typing import List, Dict
from fastapi import FastAPI, BackgroundTasks, WebSocket

app = FastAPI()

# 用于存储连接的 WebSocket 实例
connected_websockets: Dict[int, List[WebSocket]] = {}


@app.websocket("/ws/{task_id}/")
async def websocket_endpoint(websocket: WebSocket, task_id: int):
    """WebSocket路由,用于接收任务进度"""
    await websocket.accept()
    connected_websockets.setdefault(task_id, []).append(websocket)
    try:
        while True:
            await websocket.receive_text()
    except:
        connected_websockets[task_id].remove(websocket)


@app.post("/task/{task_id}/")
async def start_task(background_tasks: BackgroundTasks, task_id: int):
    """注册后台任务"""
    background_tasks.add_task(process_task, task_id=task_id)
    return {"task_id": task_id}


async def process_task(task_id):
    """处理任务的后台任务"""
    progress = 0
    while progress < 100:
        await asyncio.sleep(1)
        progress += random.randint(1, 10)
        progress = min(progress, 100)
        for ws in connected_websockets[task_id]:
            await ws.send_json({"task_id": task_id, "progress": progress})
    await asyncio.sleep(1)


# 启动应用
if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

二、执行说明

(一) 调用任务执行接口

  1. 启动服务后,访问:http://127.0.0.1:8000/docs
  2. POST请求:http://127.0.0.1:8000/task/1/,指定任务ID为1

(二) 监控任务进度

  1. 安装websocket请求工具:npm install -g wscat
  2. 终端输入wscat -c ws://127.0.0.1:8000/ws/1/,监控任务ID为1的执行进度
相关推荐
青 春 记 忆6 小时前
零基础入门python66:FastAPI AI标题、摘要和标签
python·fastapi·后端开发
青 春 记 忆7 小时前
零基础入门python65:FastAPI 安全调用大模型API
python·fastapi·后端开发
逆风飞翔的小叔7 小时前
【Python 基础】FastAPI ORM 操作MySql 实战使用详解
fastapi·fastapi orm·fastapi orm详解·fastapi orm使用·fastapi orm操作
青 春 记 忆8 小时前
零基础入门python68:FastAPI 完整博客运行与项目验收
python·fastapi·后端开发
青 春 记 忆11 小时前
零基础入门python69:为 FastAPI 项目构建可复现 Docker 镜像
python·fastapi·后端开发
the局外人14 小时前
学习 FastAPI 的 Day 2:用异步 ORM 完成增删改查
后端·python·fastapi
orient.lu14 小时前
第 24 章《WebSocket 通道》· nanobot WebSocket 通道源码深度解析:多路复用 + 重连空闲 + 媒体接入
websocket·源码解析·nanobot
2601_9622838815 小时前
Python 开发框架:Django、Flask和FastAPI
python·django·flask·fastapi·web开发
cui_ruicheng2 天前
FastAPI 应用开发(二):请求响应、Pydantic 模型与依赖注入
python·fastapi·web
卷无止境2 天前
当"精简主义"住进AI编程助手:Ponytail深度解读
后端·python·fastapi