python - 如何将 aiohttp websocket 处理程序重写为 sanic?

标签 python python-3.x aiohttp sanic

我的 aiohttp 项目中有以下 websocket 处理程序:

async def websocket_handler(request):
     ws = web.WebSocketResponse()
     await ws.prepare(request)
     request.app['websockets'].append(ws)

     async for msg in ws:
         if msg.type == aiohttp.WSMsgType.TEXT:
             if msg.data == 'close':
                 await ws.close()

         elif msg.type == aiohttp.WSMsgType.ERROR:
             logger.info('ws connection closed with exception %s' %
                            ws.exception())

     request.app['websockets'].remove(ws)
     return ws

但现在我想切换到 sanic 框架。如何重写这个方法?我不明白如何从这个 tutorial 做到这一点

最佳答案

@bp.websocket('/websocket_handler')
    async def websocket_handler(_, ws):
        self.app['web_socket'].append(ws)
        while True:
            try:
                await ws.recv()
            except ConnectionClosed:
                break

        self.app['web_socket'].remove(ws)

关于python - 如何将 aiohttp websocket 处理程序重写为 sanic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46317759/

相关文章:

python - Django 自定义表单 ImportError 即使文件位于同一目录中

python - 没有名为 'mysql' 的模块 python 问题

python - aiohttp 错误无效常量字符串

python - 如何根据小时标准获得每天每组的最小值

python-3.x - 使用 class_names 使用 graphviz 的树节点的颜色

python - 使用同一个ClientSession获取多个不同的url

python - aiohttp:如何将sub_app添加到sub_app?

python - 创建多个 numpy 数组

python - 如何找到具有最大元素数量的最大字符串类型子列表(不重复)?

python - 我如何执行 « ./bin/pip install -e . » 使用 pip ansible 命令?