本文整理汇总了Python中aiohttp.WSMsgType.ERROR属性的典型用法代码示例。如果您正苦于以下问题:Python WSMsgType.ERROR属性的具体用法?Python WSMsgType.ERROR怎么用?Python WSMsgType.ERROR使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类aiohttp.WSMsgType
的用法示例。
在下文中一共展示了WSMsgType.ERROR属性的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: view_logs
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def view_logs(server: str, token: str) -> None:
async with ClientSession() as session:
async with session.ws_connect(f"{server}/_matrix/maubot/v1/logs") as ws:
await ws.send_str(token)
try:
msg: WSMessage
async for msg in ws:
if msg.type == WSMsgType.TEXT:
if not handle_msg(msg.json()):
break
elif msg.type == WSMsgType.ERROR:
print(Fore.YELLOW + "Connection error: " + msg.data + Fore.RESET)
elif msg.type == WSMsgType.CLOSE:
print(Fore.YELLOW + "Server closed connection" + Fore.RESET)
except asyncio.CancelledError:
pass
示例2: websocket_msg_handler
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def websocket_msg_handler(self):
"""Handle active websocket connection, returning upon close"""
async for msg in self.websocket:
LOGGER.debug("Websocket message: %s, %s", msg.type, msg.data)
if msg.type in (WSMsgType.CLOSED, WSMsgType.ERROR):
return None
if msg.data == 'refresh-cache':
await self._refresh_cache()
msg = f"refreshed {BaseHandler.db_cache.dbchange['exported']}"
if self.websocket:
await self.websocket.send_str(msg)
else:
self.websocket_response_queue.add(msg)
else:
LOGGER.warning("Unhandled websocket message %s", msg.data)
示例3: receive_message
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def receive_message(self, request):
ws = web.WebSocketResponse()
await ws.prepare(request)
async for msg in ws:
if msg.type in (WSMsgType.TEXT, WSMsgType.BINARY):
self.message_results.append(json.loads(msg.data))
elif msg.type == WSMsgType.ERROR:
raise Exception(ws.exception())
return ws
示例4: service_ws_handler
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def service_ws_handler(self, request):
ws = web.WebSocketResponse(heartbeat=20.0, max_msg_size=2048)
await ws.prepare(request)
try:
async for msg in ws:
request_id = None
if msg.type == WSMsgType.TEXT:
try:
data = ujson.loads(msg.data)
if type(data) != dict:
raise InvalidRequest("Bad request (not json)")
request_id = data.get('id', None)
response = await self.service_handler(data)
except InvalidRequest as e:
response = dict(error=e.reason)
except RequestTimeout:
response = dict(error="Timeout reached without work", timeout=True)
except Exception as e:
response = dict(error=f"Unknown error, please report the following timestamp to the maintainers: {datetime.datetime.now()}")
logger.critical(traceback.format_exc())
finally:
if request_id:
response['id'] = request_id
await ws.send_json(response)
elif msg.type == WSMsgType.ERROR:
# logger.error(f"ws connection closed with exception {ws.exception()}")
pass
except Exception:
pass
# logger.info('websocket connection closed')
return ws
示例5: receive
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def receive(self):
msg = await self.ws.receive()
if msg.type == WSMsgType.TEXT:
return msg.data
elif msg.type == WSMsgType.ERROR:
raise ConnectionClosedException()
elif msg.type == WSMsgType.CLOSING:
raise ConnectionClosedException()
elif msg.type == WSMsgType.CLOSED:
raise ConnectionClosedException()
示例6: test_receive_error
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def test_receive_error(self, mock_ws):
msg = mock_ws.receive.return_value
msg.type = WSMsgType.ERROR
connection_context = AiohttpConnectionContext(ws=mock_ws)
with pytest.raises(ConnectionClosedException):
await connection_context.receive()
示例7: _ws_handler
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def _ws_handler(self, request, group):
"""
Handle websocket connections.
This includes:
* new connections
* closed connections
* messages
"""
ws_client = web.WebSocketResponse()
await ws_client.prepare(request)
session = None
if self.websockets[group]["authenticated"]:
session = await get_session(request)
if session.new:
self.logger.debug('websocket: not logged in')
if asyncio.iscoroutinefunction(ws_client.send_str):
await ws_client.send_str(json.dumps({'status': 401, 'text': "Unauthorized"}))
else:
ws_client.send_str(json.dumps({'status': 401, 'text': "Unauthorized"}))
ws_client.close()
return ws_client
ws_client.cirrina = CirrinaWSContext(request, session)
self.websockets[group]["connections"].append(ws_client)
try:
await self.websockets[group]["connect"](ws_client)
except Exception as exc:
self.logger.error("websocket: error in connect event handler")
self.logger.exception(exc)
while True:
try:
msg = await ws_client.receive()
if msg.type == WSMsgType.CLOSE or msg.type == WSMsgType.CLOSED:
self.logger.info('websocket closed')
break
self.logger.debug("websocket got: %s", msg)
if msg.type == WSMsgType.TEXT:
await self.websockets[group]["handler"](ws_client, msg.data)
elif msg.type == WSMsgType.ERROR:
self.logger.info('websocket closed with exception %s', ws_client.exception())
except futures._base.CancelledError:
pass
except Exception as exc:
self.logger.exception(exc)
self.websockets[group]["connections"].remove(ws_client)
try:
await self.websockets[group]["disconnect"](ws_client)
except Exception as exc:
self.logger.error("websocket: error in disconnect event handler")
self.logger.exception(exc)
return ws_client
# JRPC protocol
示例8: websocket_handler
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def websocket_handler(r : web.Request):
"""Handler for websocket connections and messages"""
ws = web.WebSocketResponse()
await ws.prepare(r)
# Connection Opened
ws.id = str(uuid.uuid4())
r.app['clients'][ws.id] = ws
log.server_logger.info('new connection;%s;%s;User-Agent:%s', util.get_request_ip(r), ws.id, str(
r.headers.get('User-Agent')))
try:
async for msg in ws:
if msg.type == WSMsgType.TEXT:
if msg.data == 'close':
await ws.close()
else:
reply = await handle_user_message(r, msg.data, ws=ws)
if reply is not None:
log.server_logger.debug('Sending response %s to %s', reply, util.get_request_ip(r))
await ws.send_str(reply)
elif msg.type == WSMsgType.CLOSE:
log.server_logger.info('WS Connection closed normally')
break
elif msg.type == WSMsgType.ERROR:
log.server_logger.info('WS Connection closed with error %s', ws.exception())
break
log.server_logger.info('WS connection closed normally')
except Exception:
log.server_logger.exception('WS Closed with exception')
finally:
if ws.id in r.app['clients']:
del r.app['clients'][ws.id]
for acct in r.app['subscriptions']:
if ws.id in r.app['subscriptions'][acct]:
if len(r.app['subscriptions'][acct]) == 1:
del r.app['subscriptions'][acct]
break
else:
r.app['subscriptions'][acct].remove(ws.id)
break
await ws.close()
return ws
示例9: websocket_handler
# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import ERROR [as 别名]
def websocket_handler(request):
ws = web.WebSocketResponse(timeout=0.01)
url = None
await ws.prepare(request)
async for msg in ws:
if msg.type == WSMsgType.TEXT:
try:
data = json.loads(msg.data)
except json.JSONDecodeError as e:
aux_logger.error('JSON decode error: %s', str(e))
await ws.close()
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)
await ws.close()
else:
handshake = {
'command': 'hello',
'protocols': [
'http://livereload.com/protocols/official-7',
],
'serverName': 'livereload-aiohttp',
}
await 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].add((ws, url))
else:
aux_logger.error('Unknown ws message %s', msg.data)
await ws.close()
elif msg.type == WSMsgType.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.type], msg.data)
await ws.close()
if url is None:
aux_logger.warning('browser disconnected, appears no websocket connection was made')
else:
aux_logger.debug('browser disconnected')
request.app[WS].remove((ws, url))
return ws