本文整理汇总了Python中requests.exceptions.ConnectTimeout方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ConnectTimeout方法的具体用法?Python exceptions.ConnectTimeout怎么用?Python exceptions.ConnectTimeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests.exceptions
的用法示例。
在下文中一共展示了exceptions.ConnectTimeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_302
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def get_302(url, headers=None, encoding='UTF-8'):
"""GET请求发送包装"""
try:
html = requests.get(url, headers=headers, proxies=proxies, timeout=_tiemout, allow_redirects=False)
status_code = html.status_code
if status_code == 302:
html = html.headers.get("Location", "")
elif status_code == 200:
html = html.content.decode(encoding)
html = html.replace('\x00', '').strip()
else:
html = ""
return html
except ConnectionError as e:
return "ERROR:" + "HTTP连接错误"
except ConnectTimeout as e:
return "ERROR:" + "HTTP连接超时错误"
except Exception as e:
return 'ERROR:' + str(e)
示例2: get_stream
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def get_stream(url, headers=None, encoding='UTF-8'):
"""分块接受数据"""
try:
lines = requests.get(url, headers=headers, timeout=_tiemout, stream=True, proxies=proxies)
html = list()
for line in lines.iter_lines():
if b'\x00' in line:
break
line = line.decode(encoding)
html.append(line.strip())
return '\r\n'.join(html).strip()
except ChunkedEncodingError as e:
return '\r\n'.join(html).strip()
except ConnectionError as e:
return "ERROR:" + "HTTP连接错误"
except ConnectTimeout as e:
return "ERROR:" + "HTTP连接超时错误"
except Exception as e:
return 'ERROR:' + str(e)
示例3: post_stream
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def post_stream(url, data=None, headers=None, encoding='UTF-8', files=None):
"""分块接受数据"""
try:
lines = requests.post(url, data=data, headers=headers, timeout=_tiemout, stream=True, proxies=proxies,
files=None)
html = list()
for line in lines.iter_lines():
line = line.decode(encoding)
html.append(line.strip())
return '\r\n'.join(html).strip()
except ChunkedEncodingError as e:
return '\r\n'.join(html).strip()
except ConnectionError as e:
return "ERROR:" + "HTTP连接错误"
except ConnectTimeout as e:
return "ERROR:" + "HTTP连接超时错误"
except Exception as e:
return 'ERROR:' + str(e)
示例4: test_do_api_call_succeeds_after_retrying
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def test_do_api_call_succeeds_after_retrying(self):
for exception in [requests_exceptions.ConnectionError,
requests_exceptions.SSLError,
requests_exceptions.Timeout,
requests_exceptions.ConnectTimeout,
requests_exceptions.HTTPError]:
with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
with mock.patch.object(self.hook.log, 'error') as mock_errors:
setup_mock_requests(
mock_requests,
exception,
error_count=2,
response_content={'run_id': '1'}
)
response = self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})
self.assertEqual(mock_errors.call_count, 2)
self.assertEqual(response, {'run_id': '1'})
示例5: test_do_api_call_waits_between_retries
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def test_do_api_call_waits_between_retries(self, mock_sleep):
retry_delay = 5
self.hook = DatabricksHook(retry_delay=retry_delay)
for exception in [requests_exceptions.ConnectionError,
requests_exceptions.SSLError,
requests_exceptions.Timeout,
requests_exceptions.ConnectTimeout,
requests_exceptions.HTTPError]:
with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
with mock.patch.object(self.hook.log, 'error'):
mock_sleep.reset_mock()
setup_mock_requests(mock_requests, exception)
with self.assertRaises(AirflowException):
self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})
self.assertEqual(len(mock_sleep.mock_calls), self.hook.retry_limit - 1)
calls = [
mock.call(retry_delay),
mock.call(retry_delay)
]
mock_sleep.assert_has_calls(calls)
示例6: main
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def main(host_info: dict, timeout: int = 3) -> dict:
"""
Check if host is TensorFlow Serving Model
:param host_info: host information
:param timeout: host timeout
:return: dictionary with status and data
"""
output = {"html": "", "status": ""}
try:
url = f"http://{host_info.get('ip')}:{host_info.get('port')}/v1/models"
resp = get(url, verify=False, timeout=timeout).text
except (TimeoutError, ConnectionError, ConnectTimeout, ContentDecodingError):
output.update({"status": "Timeout Error Was Caught"})
return output
if "Missing model name in request" in resp:
status = "Found TensorFlow Serving Server"
elif "404" not in resp:
status = "Possibly TensorFlow Serving Server"
else:
status = "Not TensorFlow Serving Server"
output.update({"html": resp, "status": status})
return output
示例7: test_cs_request_connect_timeout
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def test_cs_request_connect_timeout(self, mocked_wait_callback):
mocked_wait_callback.return_value = 0
self.client.session.request = mock.MagicMock(
side_effect=exceptions.ConnectTimeout)
self.client.base_url = 'https://10.10.10.10'
assert_that(calling(self.client._cs_request).with_args(
'/api/types/instance', 'GET'), raises(StoropsConnectTimeoutError))
calls = [
mock.call('GET', 'https://10.10.10.10/api/types/instance',
auth=None, files=None, verify=True, headers={}),
mock.call('GET', 'https://10.10.10.10/api/types/instance',
auth=None, files=None, verify=True, headers={}),
]
self.client.session.request.assert_has_calls(calls)
示例8: get
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def get(self, url, refer=None):
try:
resp = self.session.get(
url,
headers=self._get_headers({'Referer': refer or SMART_QQ_REFER}),
verify=SSL_VERIFY,
)
except (excps.ConnectTimeout, excps.HTTPError):
error_msg = "Failed to send finish request to `{0}`".format(
url
)
logger.exception(error_msg)
return error_msg
except requests.exceptions.SSLError:
logger.exception("SSL连接验证失败,请检查您所在的网络环境。如果需要禁用SSL验证,请修改config.py中的SSL_VERIFY为False")
else:
self._cookies.save(COOKIE_FILE, ignore_discard=True, ignore_expires=True)
return resp.text
示例9: post
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def post(self, url, data, refer=None):
try:
resp = self.session.post(
url,
data,
headers=self._get_headers({'Referer': refer or SMART_QQ_REFER}),
verify=SSL_VERIFY,
)
except requests.exceptions.SSLError:
logger.exception("SSL连接验证失败,请检查您所在的网络环境。如果需要禁用SSL验证,请修改config.py中的SSL_VERIFY为False")
except (excps.ConnectTimeout, excps.HTTPError):
error_msg = "Failed to send request to `{0}`".format(
url
)
logger.exception(error_msg)
return error_msg
else:
self._cookies.save(COOKIE_FILE, ignore_discard=True, ignore_expires=True)
return resp.text
示例10: test_no_proxy_domain_fail
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def test_no_proxy_domain_fail(self, socks5_proxy):
instance = {'proxy': {'http': 'http://1.2.3.4:567', 'no_proxy': '.google.com,example.com,example,9'}}
init_config = {}
http = RequestsWrapper(instance, init_config)
# no_proxy not match: .google.com
# ".y.com" matches "x.y.com" but not "y.com"
with pytest.raises((ConnectTimeout, ProxyError)):
http.get('http://google.com', timeout=1)
# no_proxy not match: example or example.com
with pytest.raises((ConnectTimeout, ProxyError)):
http.get('http://notexample.com', timeout=1)
with pytest.raises((ConnectTimeout, ProxyError)):
http.get('http://example.org', timeout=1)
# no_proxy not match: 9
with pytest.raises((ConnectTimeout, ProxyError)):
http.get('http://127.0.0.99', timeout=1)
示例11: get
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def get(url, headers=None, encoding='UTF-8'):
"""GET请求发送包装"""
try:
html = requests.get(url, headers=headers, proxies=proxies, timeout=_tiemout)
html = html.content.decode(encoding)
return html.replace('\x00', '').strip()
except ChunkedEncodingError as e:
html = get_stream(url, headers, encoding)
return html
except ConnectionError as e:
return "ERROR:" + "HTTP连接错误"
except ConnectTimeout as e:
return "ERROR:" + "HTTP连接超时错误"
except Exception as e:
return 'ERROR:' + str(e)
示例12: post
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def post(url, data=None, headers=None, encoding='UTF-8', files=None):
"""POST请求发送包装"""
try:
html = requests.post(url, data=data, headers=headers, proxies=proxies, timeout=_tiemout, files=files)
html = html.content.decode(encoding)
return html.replace('\x00', '').strip()
except ChunkedEncodingError as e:
html = post_stream(url, data, headers, encoding, files)
return html
except ConnectionError as e:
return "ERROR:" + "HTTP连接错误"
except ConnectTimeout as e:
return "ERROR:" + "HTTP连接超时错误"
except Exception as e:
return 'ERROR:' + str(e)
示例13: test_safe_timeout
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def test_safe_timeout(self):
"""App Integration - Safe Timeout"""
# pylint: disable=no-self-use
@safe_timeout
def _test():
raise ConnectTimeout(response='too slow')
assert_equal(_test(), (False, None))
示例14: test_do_api_call_retries_with_retryable_error
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def test_do_api_call_retries_with_retryable_error(self):
for exception in [requests_exceptions.ConnectionError,
requests_exceptions.SSLError,
requests_exceptions.Timeout,
requests_exceptions.ConnectTimeout,
requests_exceptions.HTTPError]:
with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
with mock.patch.object(self.hook.log, 'error') as mock_errors:
setup_mock_requests(mock_requests, exception)
with self.assertRaises(AirflowException):
self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})
self.assertEqual(mock_errors.call_count, self.hook.retry_limit)
示例15: QA_fetch_huobi_symbols
# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import ConnectTimeout [as 别名]
def QA_fetch_huobi_symbols():
"""
Get Symbol and currencies
"""
url = urljoin(Huobi_base_url, "/v1/common/symbols")
retries = 1
datas = list()
while (retries != 0):
try:
req = requests.get(url, timeout=TIMEOUT)
retries = 0
except (ConnectTimeout, ConnectionError, SSLError, ReadTimeout):
retries = retries + 1
if (retries % 6 == 0):
print(ILOVECHINA)
print("Retry get_exchange_info #{}".format(retries - 1))
time.sleep(0.5)
if (retries == 0):
msg_dict = json.loads(req.content)
if (('status' in msg_dict) and (msg_dict['status'] == 'ok')
and ('data' in msg_dict)):
if len(msg_dict["data"]) == 0:
return []
for symbol in msg_dict["data"]:
# 只导入上架交易对
if (symbol['state'] == 'online'):
datas.append(symbol)
return datas