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

如何让Kivy应用与FastAPI/uvicorn在同一asyncio事件循环并行运行?

解决Kivy与FastAPI/Uvicorn异步并行运行问题

你的问题出在uvicorn.run()是阻塞式调用,它会启动自己的asyncio事件循环并占据主线程,导致后续Kivy的事件循环代码根本无法执行,同时引发循环冲突错误。要让两者共用同一个事件循环并行运行,需要改用uvicorn的异步启动方式,结合asyncio.gather()同时调度两个任务。

修正后的代码示例

import asyncio
from fastapi import FastAPI
from ui.app import SuperhirnApp
from uvicorn import Config, Server

api = FastAPI()
app = SuperhirnApp(api=api)

# 示例FastAPI路由
@api.get("/")
async def root():
    return {"message": "FastAPI + Kivy 联机服务已启动"}

async def main():
    # 配置uvicorn服务器(非阻塞模式)
    uvicorn_config = Config(app=api, host="0.0.0.0", port=8000)
    server = Server(uvicorn_config)
    
    # 并行运行uvicorn服务和Kivy应用
    await asyncio.gather(
        server.serve(),
        app.async_run(async_lib="asyncio")
    )

if __name__ == "__main__":
    asyncio.run(main())

关键说明

  • 用uvicorn.Server和Config替代uvicorn.run(),避免启动独立的阻塞事件循环。
  • asyncio.gather()会将uvicorn的serve()协程和Kivy的async_run()协程加入同一个事件循环,实现并行执行。
  • 确保Kivy的async_run()指定async_lib="asyncio",让它复用当前的事件循环而非创建新循环。

内容的提问来源于stack exchange,提问作者henrik-dmg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:40:04