serve.py 文件源码

python
阅读 30 收藏 0 点赞 0 评论 0

项目:aiohttp_runserver 作者: samuelcolvin 项目源码 文件源码
def websocket_handler(request):
    ws = web.WebSocketResponse()
    url = None
    await ws.prepare(request)
    ws_type_lookup = {k.value: v for v, k in MsgType.__members__.items()}

    async for msg in ws:
        if msg.tp == MsgType.text:
            try:
                data = json.loads(msg.data)
            except json.JSONDecodeError as e:
                aux_logger.error('JSON decode error: %s', str(e))
            else:
                command = data['command']
                if command == 'hello':
                    if 'http://livereload.com/protocols/official-7' not in data['protocols']:
                        aux_logger.error('live reload protocol 7 not supported by client %s', msg.data)
                        ws.close()
                    else:
                        handshake = {
                            'command': 'hello',
                            'protocols': [
                                'http://livereload.com/protocols/official-7',
                            ],
                            'serverName': 'livereload-aiohttp',
                        }
                        ws.send_str(json.dumps(handshake))
                elif command == 'info':
                    aux_logger.debug('browser connected: %s', data)
                    url = data['url'].split('/', 3)[-1]
                    request.app[WS].append((ws, url))
                else:
                    aux_logger.error('Unknown ws message %s', msg.data)
        elif msg.tp == MsgType.error:
            aux_logger.error('ws connection closed with exception %s',  ws.exception())
        else:
            aux_logger.error('unknown websocket message type %s, data: %s', ws_type_lookup[msg.tp], msg.data)

    aux_logger.debug('browser disconnected')
    if url:
        request.app[WS].remove((ws, url))
    return ws
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号