本文整理汇总了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
示例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
示例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
示例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)
示例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}')
示例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
示例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
示例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
示例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")
示例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()
示例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()
示例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())
示例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
示例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()
示例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()