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