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


Python aiohttp.ClientConnectorError方法代码示例

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


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

示例1: convert

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def convert(ctx: Context, url: str) -> str:
        """This converter checks whether the given URL can be reached with a status code of 200."""
        try:
            async with ctx.bot.http_session.get(url) as resp:
                if resp.status != 200:
                    raise BadArgument(
                        f"HTTP GET on `{url}` returned status `{resp.status}`, expected 200"
                    )
        except CertificateError:
            if url.startswith('https'):
                raise BadArgument(
                    f"Got a `CertificateError` for URL `{url}`. Does it support HTTPS?"
                )
            raise BadArgument(f"Got a `CertificateError` for URL `{url}`.")
        except ValueError:
            raise BadArgument(f"`{url}` doesn't look like a valid hostname to me.")
        except ClientConnectorError:
            raise BadArgument(f"Cannot connect to host with URL `{url}`.")
        return url 
开发者ID:python-discord,项目名称:bot,代码行数:21,代码来源:converters.py

示例2: get_cat_image_url

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def get_cat_image_url(timeout: float) -> str:
    api_url = 'http://thecatapi.com/api/images/get'
    async with aiohttp.ClientSession() as session:
        while True:
            try:
                async with session.get(
                    api_url, params={'format': 'xml', 'type': 'jpg,png'}
                ) as res:
                    if res.status != 200:
                        raise APIServerError
                    xml_result = await res.read()
                    tree = etree.fromstring(xml_result)
                    url = tree.find('data/images/image/url').text
            except aiohttp.client_exceptions.ServerDisconnectedError:
                await asyncio.sleep(0.1)
                continue
            try:
                async with async_timeout.timeout(timeout=timeout):
                    async with session.get(url) as res:
                        async with res:
                            if res.status == 200:
                                return url
            except (aiohttp.ClientConnectorError, asyncio.TimeoutError):
                continue 
开发者ID:item4,项目名称:yui,代码行数:26,代码来源:animal.py

示例3: get_dog_image_url

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def get_dog_image_url(timeout: float) -> str:
    api_url = 'https://dog.ceo/api/breeds/image/random'
    async with aiohttp.ClientSession() as session:
        while True:
            try:
                async with session.get(api_url) as res:
                    if res.status != 200:
                        raise APIServerError
                    data = await res.json(loads=json.loads)
                    url = data['message']
            except aiohttp.client_exceptions.ServerDisconnectedError:
                await asyncio.sleep(0.1)
                continue
            try:
                async with async_timeout.timeout(timeout=timeout):
                    async with session.get(url) as res:
                        async with res:
                            if res.status == 200:
                                return url
            except (aiohttp.ClientConnectorError, asyncio.TimeoutError):
                continue 
开发者ID:item4,项目名称:yui,代码行数:23,代码来源:animal.py

示例4: get_stratz_match

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def get_stratz_match(match_id):
	url = f"https://api.stratz.com/api/v1/match/{match_id}"
	cached_data = httpgetter.cache.get(url, "json")
	
	if cached_data:
		if is_stratz_parsed(cached_data):
			return cached_data
		else:
			await httpgetter.cache.remove(url)

	try:
		return await httpgetter.get(url, cache=True, errors={
			500: "Looks like something wrong with the STRATZ api",
			204: "STRATZ hasn't recieved this match yet. Try again a bit later"
		})
	except aiohttp.ClientConnectorError:
		print("ClientConnectorError on stratz api result")
		raise StratzMatchNotParsedError(match_id) 
开发者ID:mdiller,项目名称:MangoByte,代码行数:20,代码来源:dotastats.py

示例5: analyze_nodes

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def analyze_nodes(self, address, port):
        found_nodes = []
        async with self.semaphore:
            full_host = f'http://{address}:{port}'
            self.logger.info(f'[+] Scanning host at {full_host}')
            try:
                async with aiohttp.ClientSession(loop=asyncio.get_event_loop(), timeout=self.timeout) as client:
                    ros_master_client = ServerProxy(full_host, client=client)
                    code, msg, val = await ros_master_client.getSystemState('')
                    if code == 1:
                        nodes = list(map(lambda x: x[0], map(lambda x: x[1], reduce(lambda x, y: x + y, val))))
                        for node in nodes:
                            if node in self.rosin_nodes:
                                found_nodes.append(node)
                if len(found_nodes) > 0:
                    ros_host = ROSHost(address, port)
                    ros_host.nodes = found_nodes
                    self.hosts.append(ros_host)
            except ClientConnectorError:
                self.logger.debug(f'[-] Unable to connect to host {address}')
            except Exception as e:
                ex, msg, tb = sys.exc_info()
                traceback.print_tb(tb)
                self.logger.debug(f'[-] Connection error on host {address}') 
开发者ID:aliasrobotics,项目名称:aztarna,代码行数:26,代码来源:scanner.py

示例6: test_single_proxy

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def test_single_proxy(self, proxy):
        """
        text one proxy, if valid, put them to usable_proxies.
        """
        try:
            async with aiohttp.ClientSession() as session:
                try:
                    if isinstance(proxy, bytes):
                        proxy = proxy.decode('utf-8')
                    real_proxy = 'http://' + proxy
                    print('Testing', proxy)
                    async with session.get(self.test_api, proxy=real_proxy, timeout=get_proxy_timeout) as response:
                        if response.status == 200:
                            self._conn.put(proxy)
                            print('Valid proxy', proxy)
                except (ProxyConnectionError, TimeoutError, ValueError):
                    print('Invalid proxy', proxy)
        except (ServerDisconnectedError, ClientResponseError,ClientConnectorError) as s:
            print(s)
            pass 
开发者ID:Germey,项目名称:ProxyPool,代码行数:22,代码来源:schedule.py

示例7: post_one

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def post_one(item, headers, session):
    payload = {
        'actionType': 'APPEND',
        'entities': item
    }

    payload = dumps(payload)

    url = orion + '/v2/op/update'
    try:
        async with session.post(url, headers=headers, data=payload) as response:
            status = response.status
    except ClientConnectorError:
        return 'connection problem'
    except ToE:
        return 'timeout problem'

    if status not in http_ok:
        return 'response code ' + str(status)

    return True 
开发者ID:FIWARE,项目名称:data-models,代码行数:23,代码来源:portugal_weather_forecast.py

示例8: post_one

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def post_one(el, headers, session):
    payload = {
        'actionType': 'APPEND',
        'entities': el
    }

    payload = dumps(payload)

    url = orion + '/v2/op/update'
    try:
        async with session.post(url, headers=headers, data=payload) as response:
            status = response.status
    except ClientConnectorError:
        return 'connection problem'
    except ToE:
        return 'timeout problem'

    if status not in http_ok:
        return 'response code ' + str(status)

    return True 
开发者ID:FIWARE,项目名称:data-models,代码行数:23,代码来源:spain_weather_stations.py

示例9: test_exceptions

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [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_proxy_failure_async

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def test_proxy_failure_async(self):
        client: WebClient = WebClient(
            token=self.bot_token,
            proxy=self.proxy,
            run_async=True
        )
        with self.assertRaises(ClientConnectorError):
            await client.auth_test() 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:10,代码来源:test_issue_714.py

示例11: test_fail_proxy_request

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def test_fail_proxy_request(aa_fail_proxy_config, s3_client):
    # based on test_can_make_request

    with pytest.raises(aiohttp.ClientConnectorError):
        await s3_client.list_buckets() 
开发者ID:aio-libs,项目名称:aiobotocore,代码行数:7,代码来源:test_basic_s3.py

示例12: test_resolve_host_fail

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def test_resolve_host_fail(loop, remote_resolve):
    tr, proto = mock.Mock(name='transport'), mock.Mock(name='protocol')

    with mock.patch('aiosocks.connector.create_connection',
                    make_mocked_coro((tr, proto))):
        req = ProxyClientRequest(
            'GET', URL('http://python.org'), loop=loop,
            proxy=URL('socks5://proxy.example'))
        connector = ProxyConnector(loop=loop, remote_resolve=remote_resolve)
        connector._resolve_host = make_mocked_coro(raise_exception=OSError())

        with pytest.raises(aiohttp.ClientConnectorError):
            await connector.connect(req, [], ClientTimeout()) 
开发者ID:nibrag,项目名称:aiosocks,代码行数:15,代码来源:test_connector.py

示例13: running

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def running(self):
        """Start websocket connection."""
        try:
            async with self.session.ws_connect(
                self.url, ssl=self.ssl_context, heartbeat=15
            ) as ws:
                self.state = STATE_RUNNING

                async for msg in ws:

                    if self.state == STATE_STOPPED:
                        break

                    if msg.type == aiohttp.WSMsgType.TEXT:
                        self._data = json.loads(msg.data)
                        self.session_handler_callback(SIGNAL_DATA)
                        LOGGER.debug(msg.data)

                    elif msg.type == aiohttp.WSMsgType.CLOSED:
                        LOGGER.warning("AIOHTTP websocket connection closed")
                        break

                    elif msg.type == aiohttp.WSMsgType.ERROR:
                        LOGGER.error("AIOHTTP websocket error")
                        break

        except aiohttp.ClientConnectorError:
            if self.state != STATE_STOPPED:
                LOGGER.error("Client connection error")
                self.state = STATE_DISCONNECTED

        except Exception as err:
            if self.state != STATE_STOPPED:
                LOGGER.error("Unexpected error %s", err)
                self.state = STATE_DISCONNECTED

        else:
            if self.state != STATE_STOPPED:
                self.state = STATE_DISCONNECTED 
开发者ID:Kane610,项目名称:aiounifi,代码行数:41,代码来源:websocket.py

示例14: running

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def running(self):
        """Start websocket connection."""
        url = f"http://{self.host}:{self.port}"

        try:
            async with self.session.ws_connect(url, heartbeat=15) as ws:
                self.state = STATE_RUNNING

                async for msg in ws:

                    if self.state == STATE_STOPPED:
                        break

                    elif msg.type == aiohttp.WSMsgType.TEXT:
                        self._data = json.loads(msg.data)
                        self.session_handler_callback("data")
                        LOGGER.debug(msg.data)

                    elif msg.type == aiohttp.WSMsgType.CLOSED:
                        LOGGER.warning("pydeCONZ websocket connection closed")
                        break

                    elif msg.type == aiohttp.WSMsgType.ERROR:
                        LOGGER.error("pydeCONZ websocket error")
                        break

        except aiohttp.ClientConnectorError:
            LOGGER.error("Client connection error")
            if self.state != STATE_STOPPED:
                self.retry()

        except Exception as err:
            LOGGER.error("Unexpected error %s", err)
            if self.state != STATE_STOPPED:
                self.retry()

        else:
            if self.state != STATE_STOPPED:
                self.retry() 
开发者ID:Kane610,项目名称:deconz,代码行数:41,代码来源:websocket.py

示例15: listen

# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import ClientConnectorError [as 别名]
def listen(slack_client, url):
    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(3)) as session:
        print(f"connecting to {url}")
        try:
            ws = await session.ws_connect(url)
        except (aiohttp.ClientConnectorError, asyncio.TimeoutError):
            print(f"failed to connect to {url}")
            return
        print(f"connected to {url}")

        async for msg in ws:
            r = json.loads(msg.data)
            try:
                queries = r["api"]["search"]["interrupted_queries"]
            except KeyError:
                continue

            for q in queries:
                # clean = re.sub(r"\s+", " ", q)
                clean = sqlparse.format(q, reindent=True, keyword_case='upper')
                print(f'{url}: {clean}')
                response = await slack_client.chat_postMessage(
                    username=url,
                    icon_emoji=":hourglass_flowing_sand:",
                    channel='#clubhouse-de-obscure',
                    text="*Query timed out:* " + clean
                )
                if not response["ok"]:
                    print("SLACK ERROR:\n", response)
                print() 
开发者ID:lbryio,项目名称:lbry-sdk,代码行数:32,代码来源:monitor_slow_queries.py


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