首页 > 解决方案 > 异步事件/条件不适用于 aiohttp?

问题描述

以下是服务器的简化版本,它定期为任何连接的客户端提供 json 字符串形式的遥测数据。这是我最初的尝试,其中循环将数据推送到所有连接的客户端。但是,我不能简单地让处理程序在“注册”客户端后终止。连接将被关闭。所以我需要阻塞处理程序,直到主循环确定客户端已断开连接。通过 Event 向处理程序发送信号根本不做任何事情。

@routes.get('/telemetry/json')
async def handler(request: Request):
    global CLIENT
    CLIENT = await StreamResponse().prepare(request)
    log.debug(f"Wait for {EVENT}")
    await EVENT.wait()  # This never wakes up!
    log.debug(f"Client {request.remote} disconnected")


async def main():
    global EVENT
    EVENT = Event()
    app = web.Application()
    app.add_routes(routes)
    runner = web.AppRunner(app)
    await runner.setup()
    await web.TCPSite(runner, port=8080).start()
    while True:
        await sleep(1)
        if CLIENT is None:
            continue
        try:
            await CLIENT.write('FLUSH\n'.encode('utf-8'))
            await CLIENT.drain()
        except ConnectionResetError:
            log.debug(f"Notify {EVENT}")
            EVENT.set()


log.addHandler(logging.StreamHandler())
log.setLevel(10)
asyncio.run(main())

澄清一下:全局CLIENT 和 EVENT 的使用不是它的意图。删除了对多个客户端的处理,以使示例代码尽可能短。

标签: pythonpython-asyncioaiohttp

解决方案


推荐阅读