Ejemplo n.º 1
0
async def main_ws(request):
    ws = WebSocketResponse()

    session = await get_session(request)
    expires = session.get('expires', 0)
    await ws.prepare(request)
    if expires < time():
        await ws.close(code=4403)
        return ws

    user = '******'.format(
        **session['user']).strip(' ')
    logger.info('ws connection from %s', user)
    json_str = await request.app['pg'].fetchval(calls_sql)
    await ws.send_str(json_str or '[]')
    request.app['ws_propagator'].add_ws(ws)
    try:
        async for msg in ws:
            logger.info('ws message:', msg)
            if msg.tp == WSMsgType.ERROR:
                logger.warning('ws connection closed with exception %s',
                               ws.exception())
    except CancelledError:
        pass
    finally:
        request.app['ws_propagator'].remove_ws(ws)
        logger.info('websocket disconnected: %s', user)
    return ws
Ejemplo n.º 2
0
async def websocket_handler(request):
    """
    Handle websocket connections
    """
    ws = WebSocketResponse()
    await ws.prepare(request)

    logger.info("New websocket connection")
    request.app["websockets"].add(ws)
    snapshot_processor = request.app["snapshot_processor"]

    async for msg in ws:

        if msg.type == aiohttp.WSMsgType.TEXT:
            try:
                message = msg.json()
            except (TypeError, ValueError):
                await ws.send_json({"success": False, "message": "Can't load provided JSON"})
            else:
                await snapshot_processor.process_user_message(ws, message)

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

    logger.info("Websocket disconnect. Cleaning")
    await snapshot_processor.unsubscribe(ws)
    request.app["websockets"].remove(ws)

    return ws
Ejemplo n.º 3
0
 async def listen_for_close(self, ws: WebSocketResponse) -> None:
     async for msg in ws:
         if msg.type == aiohttp.WSMsgType.TEXT:
             if msg.data == 'close':
                 await ws.close()
                 logger.info("closed websocket")
             if msg.data == 'pong':
                 self.pong_event.set()
         elif msg.type == aiohttp.WSMsgType.ERROR:
             logger.error('ws connection closed with exception %s' %
                          ws.exception())
Ejemplo n.º 4
0
class WebsocketHandler:

    def __init__(self, request):
        self.request = request
        self.remote = request.remote
        self.peername = request.transport.get_extra_info('peername')
        self.pubsub = request.app['pubsub']
        self.response = WebSocketResponse()

    def __repr__(self):
        return f"<WebsocketSubscriber {self.remote}: {self.peername}>"

    async def send_metric(self, key, value):
        message = json_dumps({key: value})
        await self.response.send_str(message)

    async def send_json(self, *a, **kw):
        data = dict(*a, **kw)
        message = json_dumps(data)
        await self.response.send_str(message)

    async def loop(self):
        await self.response.prepare(self.request)
        logger.debug("ws prepared")

        async for msg in self.response:
            if msg.type == WSMsgType.TEXT:
                try:
                    data = json.loads(msg.data)
                    self._parse_command(data)
                except Exception as e:
                    await self.send_json(error=format_exception(e))
                    logger.exception('Exception in message %r', msg)
            elif msg.type == WSMsgType.ERROR:
                logger.error('ws connection closed with exception %s',
                             self.response.exception())
                break
            else:
                logger.warning("ws message: %s", msg)

        self.pubsub.unsubscribe(self)
        logger.debug("Websocket closed: %r", self)
        return self.response

    def _parse_command(self, data):
        if 'subscribe' in data and isinstance(data['subscribe'], str):
            self.pubsub.subscribe(data['subscribe'], self)
        else:
            raise ValueError("invalid command")