python - 异步事件/条件不适用于 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 的使用不是它的意图。删除了对多个客户端的处理,以使示例代码尽可能短。
解决方案
推荐阅读
- python - Django 像用户表单一样轮询应用程序管理员
- python - 为什么 Pandas DataFrame Index 的副本保持依赖?
- javascript - 在函数中使用后保留参数的值
- r - 并排粘贴 2 个数据框,无需任何键
- sas - 如何在 SAS 中自定义箱线图?
- swift - 快速初始化嵌套字典
- node.js - Google Api 服务帐户 "error":"invalid_grant","error_description":"无效的 JWT 签名。"
- google-bigquery - BigQuery 传输与 BigQuery 负载
- flutter - 如何在 Flutter 中重新加载包含新内容的页面?
- c# - MongoDB C# Methode 搜索文档(T 型文档)