本文整理汇总了Python中urllib3.exceptions.MaxRetryError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.MaxRetryError方法的具体用法?Python exceptions.MaxRetryError怎么用?Python exceptions.MaxRetryError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib3.exceptions
的用法示例。
在下文中一共展示了exceptions.MaxRetryError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: on_get
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def on_get(self, req, resp, ical_key):
"""Access the oncall calendar identified by the key.
The response is in ical format and this url is intended to be
supplied to any calendar application that can subscribe to
calendars from the internet.
"""
try:
path = self.base_url + '/api/v0/ical/' + ical_key
if req.query_string:
path += '?%s' % req.query_string
result = self.oncall_client.get(path)
except MaxRetryError as ex:
logger.error(ex)
else:
if result.status_code == 200:
resp.status = falcon.HTTP_200
resp.content_type = result.headers['Content-Type']
resp.body = result.content
return
elif 400 <= result.status_code <= 499:
resp.status = falcon.HTTP_404
return
raise falcon.HTTPInternalServerError('Internal Server Error', 'Invalid response from API')
示例2: on_post
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def on_post(self, req, resp):
"""
Accept twilio SMS webhook and forward to iris API
"""
try:
path = self.config['iris']['hook']['twilio_messages']
re = self.iclient.post(path, req.context['body'].decode('utf-8'), raw=True)
except MaxRetryError as e:
logger.error(e.reason)
self.return_twixml_message('Connection error to web hook.', resp)
return
if re.status != 200:
self.return_twixml_message(
'Got status code: %d, content: %s' % (re.status,
re.data[0:100]), resp)
return
else:
body = process_api_response(re.data)
self.return_twixml_message(body, resp)
return
示例3: __call__
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def __call__(self, req, resp):
path = self.base_url + '/api/v0/' + '/'.join(req.path.split('/')[4:])
if req.query_string:
path += '?%s' % req.query_string
try:
if req.method == 'GET':
result = self.oncall_client.get(path)
elif req.method == 'OPTIONS':
return
else:
raise falcon.HTTPMethodNotAllowed(['GET', 'OPTIONS'])
except MaxRetryError as e:
logger.error(e.reason)
raise falcon.HTTPInternalServerError('Internal Server Error', 'Max retry error, api unavailable')
if result.status_code == 400:
raise falcon.HTTPBadRequest('Bad Request', '')
elif str(result.status_code)[0] != '2':
raise falcon.HTTPInternalServerError('Internal Server Error', 'Unknown response from the api')
else:
resp.status = falcon.HTTP_200
resp.content_type = result.headers['Content-Type']
resp.body = result.content
示例4: update_node_labels
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def update_node_labels(self, node_name, input_labels):
"""
Updating node labels
Args:
node_name(str): node for which updating labels
input_labels(dict): input labels dict
Returns:
SuccessMessage(dict): API success response
"""
resp_body_succ = SuccessMessage('Update node labels', falcon.HTTP_200)
try:
existing_labels = self.get_node_labels(node_name)
update_labels = _get_update_labels(existing_labels, input_labels)
# If there is a change
if bool(update_labels):
body = {"metadata": {"labels": update_labels}}
self.client.patch_node(node_name, body)
return resp_body_succ.get_output_json()
except (ApiException, MaxRetryError) as e:
LOG.exception("An exception occurred during node labels update: " +
str(e))
raise KubernetesApiError
示例5: get_node_labels
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def get_node_labels(self, node_name):
"""
Get existing registered node labels
Args:
node_name(str): node of which getting labels
Returns:
dict: labels dict
"""
try:
response = self.client.read_node(node_name)
if response is not None:
return response.metadata.labels
else:
return {}
except (ApiException, MaxRetryError) as e:
LOG.exception("An exception occurred in fetching node labels: " +
str(e))
if hasattr(e, 'status') and str(e.status) == "404":
raise NodeNotFoundException
else:
raise KubernetesApiError
示例6: get_resource
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def get_resource(self, resource, namespace="all"):
ret, resources = None, list()
try:
ret, namespaced_resource = self._call_api_client(resource)
except ApiException as ae:
self.logger.warning("resource autocomplete disabled, encountered "
"ApiException", exc_info=1)
except (NewConnectionError, MaxRetryError, ConnectTimeoutError):
self.logger.warning("unable to connect to k8 cluster", exc_info=1)
if ret:
for i in ret.items:
if namespace == "all" or not namespaced_resource:
resources.append((i.metadata.name, i.metadata.namespace))
elif namespace == i.metadata.namespace:
resources.append((i.metadata.name, i.metadata.namespace))
return resources
示例7: test_access_token_not_in_exception_traceback
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def test_access_token_not_in_exception_traceback(self):
"""Check that access token is replaced within chained request exceptions."""
backend_name = 'ibmq_qasm_simulator'
backend = self.provider.get_backend(backend_name)
circuit = transpile(self.qc1, backend, seed_transpiler=self.seed)
qobj = assemble(circuit, backend, shots=1)
api = backend._api
exception_message = 'The access token in this exception ' \
'message should be replaced: {}'.format(self.access_token)
exception_traceback_str = ''
try:
with mock.patch.object(
HTTPConnectionPool,
'urlopen',
side_effect=MaxRetryError(
HTTPConnectionPool('host'), 'url', reason=exception_message)):
_ = api.job_submit(backend.name(), qobj.to_dict())
except RequestsApiError:
exception_traceback_str = traceback.format_exc()
self.assertTrue(exception_traceback_str)
if self.access_token in exception_traceback_str:
self.fail('Access token not replaced in request exception traceback.')
示例8: _load_server_info
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def _load_server_info(self):
def just_json(_, serialized):
return serialized
if not self._cache.get('version'):
try:
self._cache['version'] = {
'kubernetes': self.client.request('get', '/version', serializer=just_json)
}
except (ValueError, MaxRetryError) as e:
if isinstance(e, MaxRetryError) and not isinstance(e.reason, ProtocolError):
raise
if not self.client.configuration.host.startswith("https://"):
raise ValueError("Host value %s should start with https:// when talking to HTTPS endpoint" %
self.client.configuration.host)
else:
raise
self.__version = self._cache['version']
示例9: _watch_resource_loop
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def _watch_resource_loop(mode, *args):
while True:
try:
# Always wait to slow down the loop in case of exceptions
sleep(os.getenv("ERROR_THROTTLE_SLEEP", 5))
if mode == "SLEEP":
listResources(*args)
sleep(os.getenv("SLEEP_TIME", 60))
else:
_watch_resource_iterator(*args)
except ApiException as e:
if e.status != 500:
print(f"{timestamp()} ApiException when calling kubernetes: {e}\n")
else:
raise
except ProtocolError as e:
print(f"{timestamp()} ProtocolError when calling kubernetes: {e}\n")
except MaxRetryError as e:
print(f"{timestamp()} MaxRetryError when calling kubernetes: {e}\n")
except Exception as e:
print(f"{timestamp()} Received unknown exception: {e}\n")
示例10: _load_server_info
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def _load_server_info(self):
def just_json(_, serialized):
return serialized
if not self._cache.get('version'):
try:
self._cache['version'] = {
'kubernetes': self.client.request('get', '/version', serializer=just_json)
}
except (ValueError, MaxRetryError) as e:
if isinstance(e, MaxRetryError) and not isinstance(e.reason, ProtocolError):
raise
if not self.client.configuration.host.startswith("https://"):
raise ValueError("Host value %s should start with https:// when talking to HTTPS endpoint" %
self.client.configuration.host)
else:
raise
try:
self._cache['version']['openshift'] = self.client.request(
'get',
'/version/openshift',
serializer=just_json,
)
except ApiException:
pass
self.__version = self._cache['version']
示例11: test_timeout
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def test_timeout(mock_urlopen, elasticapm_client):
transport = Transport("http://localhost", timeout=5, client=elasticapm_client)
transport.start_thread()
mock_urlopen.side_effect = MaxRetryError(None, None, reason=TimeoutError())
try:
with pytest.raises(TransportException) as exc_info:
transport.send("x")
assert "timeout" in str(exc_info.value)
finally:
transport.close()
示例12: send
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def send(self, data):
response = None
headers = self._headers.copy() if self._headers else {}
headers.update(self.auth_headers)
if compat.PY2 and isinstance(self._url, compat.text_type):
url = self._url.encode("utf-8")
else:
url = self._url
try:
try:
response = self.http.urlopen(
"POST", url, body=data, headers=headers, timeout=self._timeout, preload_content=False
)
logger.debug("Sent request, url=%s size=%.2fkb status=%s", url, len(data) / 1024.0, response.status)
except Exception as e:
print_trace = True
if isinstance(e, MaxRetryError) and isinstance(e.reason, TimeoutError):
message = "Connection to APM Server timed out " "(url: %s, timeout: %s seconds)" % (
self._url,
self._timeout,
)
print_trace = False
else:
message = "Unable to reach APM Server: %s (url: %s)" % (e, self._url)
raise TransportException(message, data, print_trace=print_trace)
body = response.read()
if response.status >= 400:
if response.status == 429: # rate-limited
message = "Temporarily rate limited: "
print_trace = False
else:
message = "HTTP %s: " % response.status
print_trace = True
message += body.decode("utf8", errors="replace")
raise TransportException(message, data, print_trace=print_trace)
return response.getheader("Location")
finally:
if response:
response.close()
示例13: run
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def run(count=0):
global bot
try:
bot = Bot(multi_logs=True, selenium_local_session=False,
proxy_address_port=get_proxy(os.environ.get('INSTA_USER')), disable_image_load=True)
selenium_url = "http://%s:%d/wd/hub" % (os.environ.get('SELENIUM', 'selenium'), 4444)
bot.set_selenium_remote_session(logger=logging.getLogger(), selenium_url=selenium_url, selenium_driver=selenium_driver(selenium_url))
bot.login()
bot.set_settings()
bot.act()
except (NewConnectionError, WebDriverException) as exc:
bot.logger.warning("Exception in run: %s; try again: count=%s" % (exc, count))
if count > 3:
print("Exception in run(): %s \n %s" % (exc, traceback.format_exc()))
report_exception(exc)
else:
run(count=count + 1)
except (ProtocolError, MaxRetryError) as exc:
bot.logger.error("Abort because of %s; \n%s" % (exc, traceback.format_exc()))
return
except Exception as exc:
print("Exception in run(): %s \n %s" % (exc, traceback.format_exc()))
report_exception(exc)
finally:
print("END")
bot.end()
示例14: run
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def run(count=0):
global bot
try:
bot = Bot(multi_logs=True, selenium_local_session=False,
proxy_address_port=get_proxy(os.environ.get('INSTA_USER')), disable_image_load=False)
selenium_url = "http://%s:%d/wd/hub" % (os.environ.get('SELENIUM', 'selenium'), 4444)
bot.set_selenium_remote_session(logger=logging.getLogger(), selenium_url=selenium_url, selenium_driver=selenium_driver(selenium_url))
bot.try_first_login()
except (NewConnectionError, NewConnectionError) as exc:
bot.logger.warning("Exception in run: %s; try again: count=%s" % (exc, count))
if count > 3:
print("Exception in run(): %s \n %s" % (exc, traceback.format_exc()))
report_exception(exc)
else:
run(count=count + 1)
except (ProtocolError, MaxRetryError) as exc:
bot.logger.error("Abort because of %s; \n%s" % (exc, traceback.format_exc()))
return
except Exception as exc:
print("Exception in run(): %s \n %s" % (exc, traceback.format_exc()))
report_exception(exc)
finally:
print("END")
bot.end()
示例15: request
# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import MaxRetryError [as 别名]
def request(self, url):
"""
Client request HTTP
:param str url: request uri
:return: urllib3.HTTPResponse
"""
if self._HTTP_DBG_LEVEL <= self.__debug.level:
self.__debug.debug_request(self._headers, url, self.__cfg.method)
try:
if self.__cfg.DEFAULT_SCAN == self.__cfg.scan:
response = self.__pool.request(self.__cfg.method,
helper.parse_url(url).path,
headers=self._headers,
retries=self.__cfg.retries,
assert_same_host=True,
redirect=False)
self.cookies_middleware(is_accept=self.__cfg.accept_cookies, response=response)
else:
response = PoolManager().request(self.__cfg.method, url,
headers=self._headers,
retries=self.__cfg.retries,
assert_same_host=False,
redirect=False)
return response
except MaxRetryError:
if self.__cfg.DEFAULT_SCAN == self.__cfg.scan:
self.__tpl.warning(key='max_retry_error', url=helper.parse_url(url).path)
pass
except HostChangedError as error:
self.__tpl.warning(key='host_changed_error', details=error)
pass
except ReadTimeoutError:
self.__tpl.warning(key='read_timeout_error', url=url)
pass
except ConnectTimeoutError:
self.__tpl.warning(key='connection_timeout_error', url=url)
pass