🐍 asyncio支持
2025/10/30大约 2 分钟
实验性功能
远程call支持 async ,如下:
async def fetch_data():
await asyncio.sleep(2) # 模拟I/O操作
print("success")案例( http server )
在baseapp中启动http server
创建venv虚拟环境
参考 VENV虚拟环境 章节
安装 aiohttp
在虚拟环境中执行命令
pip install aiohttp或者在pycharm中 设置 -> Python -> 解释器 中安装 aiohttp

编写http server代码
- 在
server_common文件夹中新建http_server.py
# -*- coding: utf-8 -*-
import asyncio
from aiohttp import web
import KBEngine
app = web.Application()
# 路由
async def handle(request):
return web.Response(text="Hello KBEngine HTTP Server")
async def getEntities(request):
entities_data = []
for eid, entity in KBEngine.entities.items():
entities_data.append({
"id": eid,
"class": entity.__class__.__name__,
})
return web.json_response({"count": len(entities_data), "entities": entities_data})
app.router.add_get("/", handle)
app.router.add_get("/getEntities", getEntities)
# HTTP 服务启动函数
async def start_http_server(host="0.0.0.0", port=8001):
"""
启动 aiohttp 非阻塞 HTTP 服务
"""
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host, port)
await site.start()
print(f"[HTTP] Server started on http://{host}:{port}")- 在baseapp中的入口脚本(kbemain.py)中,导入并启动http server
提示
此处只是提供asyncio的使用案例,http server更建议放在interface app中
# -*- coding: utf-8 -*-
import asyncio
import KBEngine
import Watcher
import d_spaces
from KBEDebug import *
from http_server import start_http_server # 引入独立模块
async def onBaseAppReady(isBootstrap):
"""
KBEngine method.
baseapp已经准备好了
@param isBootstrap: 是否为第一个启动的baseapp
@type isBootstrap: BOOL
"""
INFO_MSG('onBaseAppReady: isBootstrap=%s' % isBootstrap)
# 安装监视器
Watcher.setup()
if isBootstrap:
# 创建spacemanager
KBEngine.createEntityLocally( "Spaces", {} )
# 启动 aiohttp HTTP 服务(非阻塞)
asyncio.create_task(start_http_server())
INFO_MSG("aiohttp HTTP server 已启动(非阻塞)")启动服务器
执行 start_server.sh 或 start_server.bat 启动baseapp
访问http接口
在浏览器中访问http://127.0.0.0:8001/

在浏览器中访问http://127.0.0.0:8001/getEntities

系统回调:
注意
警告:请勿乱用async ,在不了解引擎执行顺序、async 原理、系统回调时机的情况下,禁止使用async ,会造成意想不到的BUG或系统负担
警告:带有返回值的回调方法一律无法使用async ,切记!!
警告:cellapp下,一切与时间、空间相关的回调请谨慎使用async ,会有时序问题
