【问题标题】:How to rewrite aiohttp websocket handler to sanic?如何将 aiohttp websocket 处理程序重写为 sanic?
【发布时间】:2017-09-20 09:06:38
【问题描述】:

我的 aiohttp 项目中有以下 websocket handler

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

【问题讨论】:

    标签: python python-3.x aiohttp sanic


    【解决方案1】:
    @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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多