Search code examples
pythonpython-3.xaiohttpsanic

How to rewrite aiohttp websocket handler to sanic?


I have the following websocket handler in my aiohttp project:

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

But now I wanna to switch to sanic framework. How to rewrite this method? I don't understand how to do this from this tutorial


Solution

  • @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)