带有python Web框架"quart"的Websocket? [英] Websockets with the python web framework "quart"?
问题描述
我需要有关python网络框架工作的帮助, Quart ,更具体地说是websocket.我希望能够在连接时注册客户端(将其添加到python列表中),并在断开连接时注销它们(将其从python列表中删除).我在网络上能找到的最接近的东西是以下代码:
I need help with the python web frame work, Quart, more specifically the websockets. I would like to be able to register a client when it connects (add it to a python list), and unregister them (remove it from the python list) when it disconnects. The closest thing I could find on the web is this code:
connected = set()
async def handler(websocket, path):
global connected
# Register.
connected.add(websocket)
try:
# Implement logic here.
await asyncio.wait([ws.send("Hello!") for ws in connected])
await asyncio.sleep(10)
finally:
# Unregister.
connected.remove(websocket)
但这不适用于夸脱websockets.
But this does not work with quart websockets.
我们将不胜感激.
推荐答案
此修饰符用于包装websocket处理程序时,将在 connected
集中添加和删除websocket.要在当前上下文中获取websocket,必须使用websocket的 _get_current_object
方法,并且需要最后尝试以确保删除websocket,而不考虑出现任何错误.请注意, app.websocket
必须包装(在之前) collect_websocket
用法.
This decorator when used to wrap a websocket handler, will add and remove websockets from the connected
set. The _get_current_object
method of the websocket is required to get the websocket in the current context, and the try-finally is required to ensure the websocket is removed regardless of any errors that are raised. Note the app.websocket
must wrap (be before) the collect_websocket
usage.
from functools import wraps
connected = set()
def collect_websocket(func):
@wraps(func)
async def wrapper(*args, **kwargs):
global connected
connected.add(websocket._get_current_object())
try:
return await func(*args, **kwargs)
finally:
connected.remove(websocket._get_current_object())
return wrapper
@app.websocket('/ws')
@collect_websocket
async def ws():
...
我是Quart的作者.
I am the Quart author.
这篇关于带有python Web框架"quart"的Websocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!