当前位置: 首页>>代码示例>>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;未经允许,请勿转载。