當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。