當前位置: 首頁>>代碼示例>>Python>>正文


Python aiohttp.ClientConnectionError方法代碼示例

本文整理匯總了Python中aiohttp.ClientConnectionError方法的典型用法代碼示例。如果您正苦於以下問題:Python aiohttp.ClientConnectionError方法的具體用法?Python aiohttp.ClientConnectionError怎麽用?Python aiohttp.ClientConnectionError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在aiohttp的用法示例。


在下文中一共展示了aiohttp.ClientConnectionError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: make_request

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def make_request(self, method, params=None, data=None, **kwargs):
        headers = {
            "accept": "application/json",
            "Connection": "keep-alive",
            "Content-Type": "application/json"
        }
        kwargs.setdefault('headers', headers)
        kwargs.setdefault('timeout', 10)
        error = None
        try:
            response = await method(self._endpoint, params=params, data=data, **kwargs)
            return await response.json()
        except aiohttp.ClientConnectionError as e:
            print("Unable to connect to Thor-Restful server:")
            error = e
        except Exception as e:
            try:
                text = await response.text()
                error = Exception(text.strip('\n'))
            except:
                error = e
        print("Thor-Restful server Err:")
        raise error 
開發者ID:vechain,項目名稱:web3-gear,代碼行數:25,代碼來源:request.py

示例2: _wait_until_up

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def _wait_until_up(self):
        async with aiohttp.ClientSession() as session:
            for i in range(0, 30):
                if self.exitcode is not None:
                    pytest.fail('unable to start/connect to aiohttp server')
                    return

                try:
                    # we need to bypass the proxies due to monkey patches
                    await session.get(self.endpoint_url + '/ok', timeout=0.5)
                    return
                except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
                    await asyncio.sleep(0.5)
                except BaseException:
                    pytest.fail('unable to start/connect to aiohttp server')
                    raise

        pytest.fail('unable to start and connect to aiohttp server') 
開發者ID:aio-libs,項目名稱:aiobotocore,代碼行數:20,代碼來源:mock_server.py

示例3: _start

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def _start(self):
        self._thread = threading.Thread(target=self._server_entry, daemon=True)
        self._thread.start()

        async with aiohttp.ClientSession() as session:
            start = time.time()

            while time.time() - start < 10:
                if not self._thread.is_alive():
                    break

                try:
                    # we need to bypass the proxies due to monkeypatches
                    async with session.get(self.endpoint_url + '/static',
                                           timeout=_CONNECT_TIMEOUT):
                        pass
                    break
                except (asyncio.TimeoutError, aiohttp.ClientConnectionError):
                    await asyncio.sleep(0.5)
            else:
                await self._stop()  # pytest.fail doesn't call stop_process
                raise Exception("Can not start service: {}".format(
                    self._service_name)) 
開發者ID:aio-libs,項目名稱:aiobotocore,代碼行數:25,代碼來源:moto_server.py

示例4: test_client_connection_failure

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def test_client_connection_failure(rpc_context, unused_tcp_port_factory):
    client = JsonRpcClient(
        url='ws://{host}:{port}{url}'.format(
            host=rpc_context.host, port=rpc_context.port,
            url=rpc_context.url,
        )
    )

    with pytest.raises(aiohttp.ClientConnectionError):
        await client.connect_url(
            'ws://{host}:{port}{url}'.format(
                host=rpc_context.host, port=unused_tcp_port_factory(),
                url=rpc_context.url,
            )
        )
    assert client._session.closed is True 
開發者ID:pengutronix,項目名稱:aiohttp-json-rpc,代碼行數:18,代碼來源:test_client.py

示例5: fetch

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def fetch(self, url, **kwargs) -> aiohttp.ClientResponse:
        headers = {"User-Agent": get_user_agent()}
        async with aiohttp.ClientSession(
            conn_timeout=self.config["response_timeout"],
            read_timeout=self.config["response_timeout"],
        ) as session:
            try:
                async with session.get(
                    urljoin(self.host, url), headers=headers, **kwargs
                ) as response:
                    await response.text()
                    return response
            except aiohttp.ClientConnectionError:
                raise exceptions.SlaveDoesNotExist(
                    f"Unable to connect to the slave at {self.host}"
                ) 
開發者ID:Yelp,項目名稱:paasta,代碼行數:18,代碼來源:slave.py

示例6: _sync

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def _sync(self) -> None:
        if not self.is_real_user:
            self.log.warning("Called sync() for non-custom puppet.")
            return
        custom_mxid: UserID = self.custom_mxid
        access_token_at_start: str = self.access_token
        errors: int = 0
        filter_id: FilterID = await self._create_sync_filter()
        self.log.debug(f"Starting syncer for {custom_mxid} with sync filter {filter_id}.")
        while access_token_at_start == self.access_token:
            try:
                cur_batch = self.next_batch
                sync_resp = await self.intent.sync(filter_id=filter_id, since=cur_batch,
                                                   set_presence=PresenceState.OFFLINE)
                self.next_batch = sync_resp.get("next_batch", None)
                errors = 0
                if cur_batch is not None:
                    self._handle_sync(sync_resp)
            except (MatrixError, ClientConnectionError, asyncio.TimeoutError) as e:
                errors += 1
                wait = min(errors, 11) ** 2
                self.log.warning(f"Syncer for {custom_mxid} errored: {e}. "
                                 f"Waiting for {wait} seconds...")
                await asyncio.sleep(wait)
        self.log.debug(f"Syncer for custom puppet {custom_mxid} stopped.") 
開發者ID:tulir,項目名稱:mautrix-python,代碼行數:27,代碼來源:custom_puppet.py

示例7: fetch

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def fetch(self):
        while True:

            try:
                hdrlen = constants.STREAM_HEADER_SIZE_BYTES
                header = yield from self._response.content.readexactly(hdrlen)

                _, length = struct.unpack(">BxxxL", header)
                if not length:
                    continue

                data = yield from self._response.content.readexactly(length)

            except (
                aiohttp.ClientConnectionError,
                aiohttp.ServerDisconnectedError,
                asyncio.IncompleteReadError,
            ):
                break
            return data 
開發者ID:aio-libs,項目名稱:aiodocker,代碼行數:22,代碼來源:multiplexed.py

示例8: post

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def post(self, url: str, data: Dict[str, str] = None) -> Response:
        """Perform HTTP POST request.

        :param url: the request url
        :param data: the data send to server
        :return: the response from server
        :raise: :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
        """
        try:
            response = await self._session.post(url, data=data, timeout=aiohttp.ClientTimeout(total=self.post_timeout))
            return Response(
                status_code=response.status,
                text=await response.text(),
                headers=dict(response.headers),
                url=str(response.url),
            )
        except aiohttp.ClientConnectionError as e:
            raise ConnectionError(e) 
開發者ID:StellarCN,項目名稱:py-stellar-base,代碼行數:20,代碼來源:aiohttp_client.py

示例9: test_exceptions

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def test_exceptions(self):
        import aiohttp

        exceptions = aiohttp_.AiohttpClient.exceptions

        with pytest.raises(exceptions.BaseClientException):
            raise aiohttp.ClientError()

        with pytest.raises(exceptions.BaseClientException):
            # Test polymorphism
            raise aiohttp.InvalidURL("invalid")

        with pytest.raises(exceptions.ConnectionError):
            raise aiohttp.ClientConnectionError()

        with pytest.raises(exceptions.ConnectionTimeout):
            raise aiohttp.ClientConnectorError.__new__(
                aiohttp.ClientConnectorError
            )

        with pytest.raises(exceptions.ServerTimeout):
            raise aiohttp.ServerTimeoutError()

        with pytest.raises(exceptions.SSLError):
            raise aiohttp.ClientSSLError.__new__(aiohttp.ClientSSLError)

        with pytest.raises(exceptions.InvalidURL):
            raise aiohttp.InvalidURL("invalid") 
開發者ID:prkumar,項目名稱:uplink,代碼行數:30,代碼來源:test_clients.py

示例10: test_stream_reconnection_client_connection_error

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def test_stream_reconnection_client_connection_error():
    async with Stream() as stream:
        async def client_connection_error():
            raise aiohttp.ClientConnectionError

        with patch.object(stream, '_connect', side_effect=stream_content):
            data = await stream.__anext__()
            assert 'connected' in data
            with patch.object(stream.response, 'readline',
                              side_effect=client_connection_error):
                data = await stream.__anext__()
                assert data == {'reconnecting_in': ERROR_TIMEOUT,
                                'error': None} 
開發者ID:odrling,項目名稱:peony-twitter,代碼行數:15,代碼來源:test_stream.py

示例11: _check_url_async

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def _check_url_async(url: str, session: ClientSession) -> UrlResult:
    """
    Connect to URL and return response status.

    Parameters
    ----------
    url : str
        URL to check
    session : ClientSession
        aiohttp client session

    Returns
    -------
    UrlResult
        Tuple of status code, redirect history, requested url,
        status/error message.

    """
    try:
        async with session.get(url) as resp:
            try:
                await resp.read()
                if resp.history:
                    result = UrlResult(
                        resp.status,
                        resp.history,
                        url,
                        "No error. Redirect to " + str(resp.url),
                    )
                elif resp.status == 200:
                    result = UrlResult(
                        resp.status, resp.history, url, "No error. No redirect."
                    )
                else:
                    result = UrlResult(resp.status, resp.history, url, "Error?")
            except ClientResponseError as client_err:
                return UrlResult(client_err.status, [], url, client_err)
    except ClientConnectionError as err:
        result = UrlResult(404, [], url, err)
    return result 
開發者ID:microsoft,項目名稱:msticpy,代碼行數:42,代碼來源:url_checker_async.py

示例12: _group_send

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def _group_send(self, dst_url, messages):
        with self._sentry_group_message_scope(dst_url):
            LOG.info(f'send {len(messages)} messages to {dst_url}')
            data = ActorMessage.batch_encode(messages, self.content_encoding)
            try:
                async with self.session.post(dst_url, data=data, headers=self.headers) as r:
                    await r.read()
            except aiohttp.ClientConnectionError as ex:
                LOG.warning(f'failed to send message to {dst_url}: {ex}')
                return
            except aiohttp.ClientError as ex:
                LOG.warning(f'failed to send message to {dst_url}: {ex}')
                raise
            aiohttp_raise_for_status(r) 
開發者ID:anyant,項目名稱:rssant,代碼行數:16,代碼來源:client.py

示例13: handle_exception

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def handle_exception():
    """
    Context manager translating network related exceptions
    to custom :mod:`~galaxy.api.errors`.
    """
    try:
        yield
    except asyncio.TimeoutError:
        raise BackendTimeout()
    except aiohttp.ServerDisconnectedError:
        raise BackendNotAvailable()
    except aiohttp.ClientConnectionError:
        raise NetworkError()
    except aiohttp.ContentTypeError:
        raise UnknownBackendResponse()
    except aiohttp.ClientResponseError as error:
        if error.status == HTTPStatus.UNAUTHORIZED:
            raise AuthenticationRequired()
        if error.status == HTTPStatus.FORBIDDEN:
            raise AccessDenied()
        if error.status == HTTPStatus.SERVICE_UNAVAILABLE:
            raise BackendNotAvailable()
        if error.status == HTTPStatus.TOO_MANY_REQUESTS:
            raise TooManyRequests()
        if error.status >= 500:
            raise BackendError()
        if error.status >= 400:
            logging.warning(
                "Got status %d while performing %s request for %s",
                error.status, error.request_info.method, str(error.request_info.url)
            )
            raise UnknownError()
    except aiohttp.ClientError:
        logging.exception("Caught exception while performing request")
        raise UnknownError() 
開發者ID:TouwaStar,項目名稱:Galaxy_Plugin_Bethesda,代碼行數:37,代碼來源:http.py

示例14: execute_command

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def execute_command(conf, method, params, callback=display):
    async with aiohttp.ClientSession() as session:
        try:
            message = {'method': method, 'params': params}
            async with session.get(conf.api_connection_url, json=message) as resp:
                try:
                    data = await resp.json()
                    if 'result' in data:
                        return callback(data['result'])
                    elif 'error' in data:
                        return callback(data['error'])
                except Exception as e:
                    log.exception('Could not process response from server:', exc_info=e)
        except aiohttp.ClientConnectionError:
            print("Could not connect to daemon. Are you sure it's running?") 
開發者ID:lbryio,項目名稱:lbry-sdk,代碼行數:17,代碼來源:cli.py

示例15: __anext__

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientConnectionError [as 別名]
def __anext__(self):
        while True:
            try:
                data = yield from self._response.content.readline()
                if not data:
                    break
            except (aiohttp.ClientConnectionError, aiohttp.ServerDisconnectedError):
                break
            return self._transform(json.loads(data.decode("utf8")))

        raise StopAsyncIteration 
開發者ID:aio-libs,項目名稱:aiodocker,代碼行數:13,代碼來源:jsonstream.py


注:本文中的aiohttp.ClientConnectionError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。