本文整理汇总了Python中requests.ConnectTimeout方法的典型用法代码示例。如果您正苦于以下问题:Python requests.ConnectTimeout方法的具体用法?Python requests.ConnectTimeout怎么用?Python requests.ConnectTimeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.ConnectTimeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_okta_connection_timeout
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def test_okta_connection_timeout(
self,
mock_print_tty,
mock_makedirs,
mock_open,
mock_chmod
):
responses.add(
responses.POST,
'https://organization.okta.com/api/v1/authn',
body=ConnectTimeout()
)
with self.assertRaises(SystemExit):
Okta(
user_name="user_name",
user_pass="user_pass",
organization="organization.okta.com"
)
print_tty_calls = [
call("Error: Timed Out")
]
mock_print_tty.assert_has_calls(print_tty_calls)
示例2: test_retry_multiple_exceptions
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def test_retry_multiple_exceptions():
@retry((ConnectionError, ConnectTimeout), retries=4, delay=0.1)
def raise_multiple_exceptions():
counter['i'] += 1
if counter['i'] == 1:
raise ConnectionError('one error')
elif counter['i'] == 2:
raise ConnectTimeout('another error')
else:
return 'success'
counter = dict(i=0)
test_result = raise_multiple_exceptions()
assert test_result == 'success'
assert counter['i'] == 3
示例3: __call__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def __call__(self):
try:
req = requests.get(self.url, headers=self.header,
timeout=10, proxies=self.proxies)
except requests.ConnectTimeout or requests.exceptions.ReadTimeout as e:
print(f"链接{self.url}已经超时")
self.status = False
return {"status": self.status, 'html': ''}
try:
encodeing = chardet.detect(req.content)['encoding']
html = req.content.decode(encodeing, errors='replace')
except Exception as e:
print(e)
print("编码时错误,具体错误不定......")
self.status = False
return {"status": self.status, 'html': ''}
return {"status": self.status, 'html': html}
示例4: do
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def do(self, api_name=None, pk=None, method='get', use_auth=True,
data=None, params=None, content_type='application/json', **kwargs):
if api_name in API_URL_MAPPING:
path = API_URL_MAPPING.get(api_name)
if pk and '%s' in path:
path = path % pk
else:
path = api_name
request_headers = kwargs.get('headers', {})
default_headers = self.default_headers or {}
headers = {k: v for k, v in default_headers.items()}
headers.update(request_headers)
kwargs['headers'] = headers
url = self.endpoint.rstrip('/') + path
req = HttpRequest(url, method=method, data=data,
params=params, content_type=content_type,
**kwargs)
if use_auth:
if not self.auth:
msg = 'Authentication required, but not provide'
logger.error(msg)
raise RequestError(msg)
else:
self.auth.sign_request(req)
try:
resp = req.do()
except (requests.ConnectionError, requests.ConnectTimeout) as e:
msg = "Connect endpoint {} error: {}".format(self.endpoint, e)
logger.error(msg)
raise RequestError(msg)
return self.clean_result(resp)
示例5: _fetch_inventory
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def _fetch_inventory(self, inventory_url: str) -> Optional[dict]:
"""Get and return inventory from `inventory_url`. If fetching fails, return None."""
fetch_func = functools.partial(intersphinx.fetch_inventory, SPHINX_MOCK_APP, '', inventory_url)
for retry in range(1, FAILED_REQUEST_RETRY_AMOUNT+1):
try:
package = await self.bot.loop.run_in_executor(None, fetch_func)
except ConnectTimeout:
log.error(
f"Fetching of inventory {inventory_url} timed out,"
f" trying again. ({retry}/{FAILED_REQUEST_RETRY_AMOUNT})"
)
except ProtocolError:
log.error(
f"Connection lost while fetching inventory {inventory_url},"
f" trying again. ({retry}/{FAILED_REQUEST_RETRY_AMOUNT})"
)
except HTTPError as e:
log.error(f"Fetching of inventory {inventory_url} failed with status code {e.response.status_code}.")
return None
except ConnectionError:
log.error(f"Couldn't establish connection to inventory {inventory_url}.")
return None
else:
return package
log.error(f"Fetching of inventory {inventory_url} failed.")
return None
示例6: test_timeout
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def test_timeout(self):
"""
Connection timeouts to the API are handled gracefully.
"""
request_mock = self._get_exception_mock(requests.ConnectTimeout())
with mock.patch("requests.get", request_mock):
result = api.pwned_password(self.sample_password)
self.assertEqual(None, result)
示例7: call
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def call(self, endpoint=None, headers=None, json_payload=None):
print_tty(
"Info: Calling {}".format(endpoint),
silent=self.silent
)
try:
if json_payload is not None:
return self.session.post(
endpoint,
json=json_payload,
headers=headers,
timeout=10
)
else:
return self.session.get(
endpoint,
headers=headers,
timeout=10
)
except ConnectTimeout:
print_tty("Error: Timed Out")
sys.exit(1)
except ConnectionError:
print_tty("Error: Connection Error")
sys.exit(1)
示例8: do_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def do_request(self, method, url, data=None, json=True, headers=None, ignore_failure=False):
loop = asyncio.get_event_loop()
if not headers:
headers = self._authentication_client.session.headers
try:
if data is None:
data = {}
params = {
"method": method,
"url": url,
"data": data,
"timeout": self._authentication_client.timeout,
"headers": headers
}
try:
response = await loop.run_in_executor(None, functools.partial(self._authentication_client.session.request, **params))
except (requests.Timeout, requests.ConnectTimeout, requests.ReadTimeout):
raise BackendTimeout()
except requests.ConnectionError:
raise NetworkError
if not ignore_failure:
self.handle_status_code(response.status_code)
if json:
return response.json()
else:
return response
except Exception as e:
raise e
示例9: wemp_spider
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def wemp_spider(url, site):
"""
抓取微信内容
:param url:
:param site:
:return:
"""
if is_crawled_url(url):
return
try:
rsp = requests.get(url, timeout=10)
if rsp.ok:
try:
if get_host_name(rsp.url) == 'mp.weixin.qq.com':
title, author, content = parse_weixin_page(rsp)
elif 'ershicimi.com' in get_host_name(rsp.url):
title, author, content = parse_ershicimi_page(rsp)
else:
logger.warning(f'公众号域名解析异常:`{rsp.url}')
return
except:
logger.info(f'公众号内容解析异常:`{rsp.url}')
return
article = Article(title=title, author=author, site=site, uindex=current_ts(),
content=content, src_url=url)
article.save()
mark_crawled_url(url)
except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):
logger.warning(f'公众号爬取出现网络异常:`{url}')
except:
logger.warning(f'公众号爬取出现未知异常:`{url}')
示例10: save_avatar
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def save_avatar(avatar, userid, size=100):
"""
保存网络头像
:param avatar:
:param userid:
:param size:
:return: 保存后的头像地址
"""
try:
rsp = requests.get(avatar, timeout=10)
if rsp.ok:
img_obj = Image.open(BytesIO(rsp.content))
img_obj.thumbnail((size, size))
jpg = get_hash_name(userid) + '.jpg'
if img_obj.mode != 'RGB':
img_obj = img_obj.convert('RGB')
img_obj.save(os.path.join(settings.BASE_DIR, 'assets', 'avatar', jpg))
return f'/assets/avatar/{jpg}'
else:
logger.error(f"同步用户头像出现网络异常!`{userid}`{avatar}")
except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):
logger.error(f"同步用户头像网络异常!`{userid}`{avatar}")
except:
logger.error(f"同步用户头像未知异常`{userid}`{avatar}")
return '/assets/img/logo.svg'
示例11: connect
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def connect(self):
# start of main function
try:
# Establish a callback to stop the component when the stop event occurs
self.hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.stop_subscription)
self.hass.services.async_register(DOMAIN, 'alarm_panel_reconnect', self.service_panel_reconnect)
self.hass.services.async_register(DOMAIN, 'alarm_panel_eventlog', self.service_panel_eventlog, schema=ALARM_SERVICE_EVENTLOG)
self.hass.services.async_register(DOMAIN, 'alarm_panel_command', self.service_panel_command, schema=ALARM_SERVICE_COMMAND)
self.hass.services.async_register(DOMAIN, 'alarm_panel_download', self.service_panel_download)
success = self.connect_to_alarm()
if success:
# Create "alarm control panel"
# eventually there will be an "alarm control panel" for each partition but we only support 1 partition at the moment
self.hass.async_create_task( self.hass.config_entries.async_forward_entry_setup(self.entry, "alarm_control_panel") )
return True
except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Visonic Alarm Panel: %s", str(ex))
hass.components.persistent_notification.create(
'Error: {}<br />'
'You will need to restart hass after fixing.'
''.format(ex),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID)
return False
示例12: evaluate
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def evaluate(self):
"""Sends the request to the URL set in the configuration and executes
each one of the expectations, one by one. The status will be updated
according to the expectation results.
"""
try:
if self.endpoint_header is not None:
self.request = requests.request(
self.endpoint_method, self.endpoint_url, timeout=self.endpoint_timeout, headers=self.endpoint_header
)
else:
self.request = requests.request(self.endpoint_method, self.endpoint_url, timeout=self.endpoint_timeout)
self.current_timestamp = int(time.time())
except requests.ConnectionError:
self.message = "The URL is unreachable: %s %s" % (self.endpoint_method, self.endpoint_url)
self.logger.warning(self.message)
self.status = st.ComponentStatus.PARTIAL_OUTAGE
return
except requests.HTTPError:
self.message = "Unexpected HTTP response"
self.logger.exception(self.message)
self.status = st.ComponentStatus.PARTIAL_OUTAGE
return
except (requests.Timeout, requests.ConnectTimeout):
self.message = "Request timed out"
self.logger.warning(self.message)
self.status = st.ComponentStatus.PERFORMANCE_ISSUES
return
# We initially assume the API is healthy.
self.status = st.ComponentStatus.OPERATIONAL
self.message = ""
for expectation in self.expectations:
status: ComponentStatus = expectation.get_status(self.request)
# The greater the status is, the worse the state of the API is.
if status.value > self.status.value:
self.status = status
self.message = expectation.get_message(self.request)
self.logger.info(self.message)
示例13: _get_member_by_mid
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def _get_member_by_mid(self, mid: int) -> Optional[dict]:
"""
根据用户id获取其信息
:param mid: B站用户id
:return: 用户详情 or None
"""
get_params = {
'mid': mid,
'jsonp': 'jsonp'
}
try:
res_json = requests.get(API_MEMBER_INFO, params=get_params, timeout=WAIT_MAX, proxies=self.cur_proxy,
headers=self.headers).json()
except ConnectTimeout as e:
print(f'获取用户id: {mid} 详情失败: 请求接口超时, 当前代理:{self.cur_proxy["https"]}')
raise RequestException(str(e))
except ReadTimeout as e:
print(f'获取用户id: {mid} 详情失败: 接口读取超时, 当前代理:{self.cur_proxy["https"]}')
raise RequestException(str(e))
except ValueError as e:
# 解析json失败基本上就是ip被封了
print(f'获取用户id: {mid} 详情失败: 解析json出错, 当前代理:{self.cur_proxy["https"]}')
raise RequestException(str(e))
except ProxyError as e:
print(f'获取用户id: {mid} 详情失败: 连接代理失败, 当前代理:{self.cur_proxy["https"]}')
raise RequestException(str(e))
except requests.ConnectionError as e:
# 可以断定就是代理IP地址无效
print(f'获取用户id: {mid} 详情失败: 连接错误, 当前代理:{self.cur_proxy["https"]}')
raise RequestException(str(e))
except ChunkedEncodingError as e:
print(f'获取用户id: {mid} 详情失败: 远程主机强迫关闭了一个现有的连接, 当前代理:{self.cur_proxy["https"]}')
raise RequestException(str(e))
else:
if res_json['code'] == -404:
print(f'找不到用户mid:{mid}')
raise UserNotFoundException(f'找不到用户mid:{mid}')
if 'data' in res_json:
return res_json['data']
print(f'获取用户id: {mid} 详情失败: data字段不存在!')
return
示例14: test_connect_timeout
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def test_connect_timeout(self):
"""
Test that a connect timeout occurs when instantiating
a client object with a timeout of 10 ms.
"""
with self.assertRaises(ConnectTimeout) as cm:
self.set_up_client(auto_connect=True, timeout=.01)
self.assertTrue(str(cm.exception).find('timed out.'))
示例15: can_connect_to_wiktionary
# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectTimeout [as 别名]
def can_connect_to_wiktionary() -> bool:
"""Check whether WAN connection to Wiktionary is available."""
try:
requests.get("https://en.wiktionary.org/wiki/linguistics")
except (requests.ConnectionError, requests.ConnectTimeout):
return False
else:
return True