当前位置: 首页>>代码示例>>Python>>正文


Python WSMsgType.TEXT属性代码示例

本文整理汇总了Python中aiohttp.WSMsgType.TEXT属性的典型用法代码示例。如果您正苦于以下问题:Python WSMsgType.TEXT属性的具体用法?Python WSMsgType.TEXT怎么用?Python WSMsgType.TEXT使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在aiohttp.WSMsgType的用法示例。


在下文中一共展示了WSMsgType.TEXT属性的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: view_logs

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [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 
开发者ID:maubot,项目名称:maubot,代码行数:18,代码来源:logs.py

示例2: receive_message

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [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 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:14,代码来源:test_ws_transport.py

示例3: test_cloud_sending_invalid_json

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [as 别名]
def test_cloud_sending_invalid_json(mock_iot_client, caplog, cloud_mock_iot):
    """Test cloud sending invalid JSON."""
    conn = MockIoT(cloud_mock_iot)
    mock_iot_client.receive.return_value = mock_coro(
        MagicMock(type=WSMsgType.TEXT, json=MagicMock(side_effect=ValueError))
    )

    await conn.connect()

    assert "Connection closed: Received invalid JSON." in caplog.text 
开发者ID:NabuCasa,项目名称:hass-nabucasa,代码行数:12,代码来源:test_iot_base.py

示例4: read_json

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [as 别名]
def read_json(self) -> Any:
        try:
            msg = await asyncio.wait_for(
                self._ws.receive(), timeout=self._receive_timeout)
            if msg.type == WSMsgType.TEXT:
                return json.loads(msg.data)
            elif msg.type == WSMsgType.BINARY:
                return json.loads(msg.data.decode('utf8'))
        except (ClientError, asyncio.TimeoutError):
            return None
        except asyncio.CancelledError:
            # print('asyncio.CancelledError', 'read_json')
            return None
        return None 
开发者ID:yjqiang,项目名称:danmu,代码行数:16,代码来源:conn.py

示例5: service_ws_handler

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [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 
开发者ID:guilhermelawless,项目名称:nano-dpow,代码行数:35,代码来源:dpow_server.py

示例6: receive

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [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() 
开发者ID:graphql-python,项目名称:graphql-ws,代码行数:12,代码来源:aiohttp.py

示例7: test_receive_good_data

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [as 别名]
def test_receive_good_data(self, mock_ws):
        msg = mock_ws.receive.return_value
        msg.type = WSMsgType.TEXT
        msg.data = "test"
        connection_context = AiohttpConnectionContext(ws=mock_ws)
        assert await connection_context.receive() == "test" 
开发者ID:graphql-python,项目名称:graphql-ws,代码行数:8,代码来源:test_aiohttp.py

示例8: _ws_handler

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [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 
开发者ID:neolynx,项目名称:cirrina,代码行数:61,代码来源:server.py

示例9: websocket_handler

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [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 
开发者ID:appditto,项目名称:natrium-wallet-server,代码行数:48,代码来源:natriumcast.py

示例10: websocket_handler

# 需要导入模块: from aiohttp import WSMsgType [as 别名]
# 或者: from aiohttp.WSMsgType import TEXT [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 
开发者ID:aio-libs,项目名称:aiohttp-devtools,代码行数:48,代码来源:serve.py


注:本文中的aiohttp.WSMsgType.TEXT属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。