You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中回调函数内Asyncio.create_task()无法立即执行问题

问题:FastAPI WebSocket实时进度回调延迟发送的解决方法

我用FastAPI、WebSocket和Asyncio开发功能,需要通过回调函数经WebSocket向用户发送实时进度值(比如5%、10%这类)。但现在遇到的问题是:回调函数里的所有消息都要等主函数the_main_process执行完才会发送,而且我没办法修改这个主函数让它支持await。

预期流程

  • the_main_process(callback)启动
  • 每次callback()执行完成后立即发送"5%"、"10%"、"15%"等进度消息
  • the_main_process(callback)结束后发送"Finished"

实际流程

  • the_main_process(callback)启动
  • the_main_process(callback)结束后先发送"Finished"
  • 之后才依次发送callback()里的"5%"、"10%"、"15%"等进度消息

简化代码示例

app.py

from fastapi import FastAPI, WebSocket
import otherscript

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    # 将WebSocket引用传递给otherscript.py
    otherscript.websocket = websocket
    
    while True:
        # 执行otherscript.py中的my_function()
        result = otherscript.my_function()

otherscript.py

import asyncio

# 初始化WebSocket引用占位符
websocket = None

# 该回调函数在the_main_process()每执行n步时被调用,返回进度
def callback():
    body = {
        "value": "5%",
        "foo": "bar",
        # ... 其他字段
    }

    # 因为the_main_process()无法被await,callback()也不能定义为异步函数,所以用asyncio.create_task但不await
    # 现在的问题是这些回调消息都要等the_main_process()结束后才发送
    task = asyncio.create_task(websocket.send_json(body))

def my_function():
    # 这个带回调的函数我没法控制,是一个不支持await的torch多线程相关函数
    result = the_main_process(arg1, arg2, ..., callback)
    
    # 这条消息会比所有回调消息先发送
    task = asyncio.create_task(websocket.send_text("Finished"))
    return result       

我猜测是回调里创建的任务都被加到了Asyncio队列的主进程任务之后,所以才会延迟执行。请问有什么解决思路吗?是不是我的代码结构有问题?


内容的提问来源于stack exchange,提问作者Yann Masoch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 00:38:24