本文整理汇总了Python中six.moves.http_client.HTTPException方法的典型用法代码示例。如果您正苦于以下问题:Python http_client.HTTPException方法的具体用法?Python http_client.HTTPException怎么用?Python http_client.HTTPException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.http_client
的用法示例。
在下文中一共展示了http_client.HTTPException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _password_client
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def _password_client(self, body=None, headers=None, decode=True):
"""Client for the Password Server."""
port = CONF.cloudstack.password_server_port
with contextlib.closing(http_client.HTTPConnection(
self._metadata_host, port, timeout=TIMEOUT)) as connection:
try:
connection.request("GET", "/", body=body, headers=headers)
response = connection.getresponse()
except http_client.HTTPException as exc:
LOG.error("Request failed: %s", exc)
raise
content = response.read()
if decode:
content = encoding.get_as_string(content)
if response.status != 200:
raise http_client.HTTPException(
"%(status)s %(reason)s - %(message)r",
{"status": response.status, "reason": response.reason,
"message": content})
return content
示例2: test_refresh_failure_http_error
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def test_refresh_failure_http_error(self, mock_donor_credentials):
credentials = self.make_credentials(lifetime=None)
response_body = {}
request = self.make_request(
data=json.dumps(response_body), status=http_client.HTTPException
)
with pytest.raises(exceptions.RefreshError) as excinfo:
credentials.refresh(request)
assert excinfo.match(impersonated_credentials._REFRESH_ERROR)
assert not credentials.valid
assert credentials.expired
示例3: _refresh
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def _refresh(self, http):
"""Refreshes the access token.
Skip all the storage hoops and just refresh using the API.
Args:
http: an object to be used to make HTTP requests.
Raises:
HttpAccessTokenRefreshError: When the refresh fails.
"""
try:
self._retrieve_info(http)
self.access_token, self.token_expiry = _metadata.get_token(
http, service_account=self.service_account_email)
except http_client.HTTPException as err:
raise client.HttpAccessTokenRefreshError(str(err))
示例4: check_server
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def check_server(host, port, path_info='/', timeout=3, retries=30):
"""Perform a request until the server reply"""
if retries < 0:
return 0
conn = http_client.HTTPConnection(host, port, timeout=timeout)
time.sleep(.3)
for i in range(retries):
try:
conn.request('GET', path_info)
res = conn.getresponse()
return res.status
except (socket.error, http_client.HTTPException):
time.sleep(.3)
return 0
示例5: open_url
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def open_url(self, url, warning=None):
if url.startswith('file:'):
return local_open(url)
try:
return open_with_auth(url, self.opener)
except (ValueError, http_client.InvalidURL) as v:
msg = ' '.join([str(arg) for arg in v.args])
if warning:
self.warn(warning, msg)
else:
raise DistutilsError('%s %s' % (url, msg))
except urllib.error.HTTPError as v:
return v
except urllib.error.URLError as v:
if warning:
self.warn(warning, v.reason)
else:
raise DistutilsError("Download error for %s: %s"
% (url, v.reason))
except http_client.BadStatusLine as v:
if warning:
self.warn(warning, v.line)
else:
raise DistutilsError(
'%s returned a bad status line. The server might be '
'down, %s' %
(url, v.line)
)
except (http_client.HTTPException, socket.error) as v:
if warning:
self.warn(warning, v)
else:
raise DistutilsError("Download error for %s: %s"
% (url, v))
示例6: retry
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def retry(func):
def wrapped(*args, **kwargs):
count = 0
while True:
try:
return func(*args, **kwargs)
except (HTTPException, HTTPError, socket.error, socket.timeout):
if count >= 10:
raise
logger.info('Throttling API requests...')
time.sleep(2 ** count * 0.5)
count += 1
return wrapped
示例7: get
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def get(http, path, root=METADATA_ROOT, recursive=None):
"""Fetch a resource from the metadata server.
Args:
http: an object to be used to make HTTP requests.
path: A string indicating the resource to retrieve. For example,
'instance/service-accounts/default'
root: A string indicating the full path to the metadata server root.
recursive: A boolean indicating whether to do a recursive query of
metadata. See
https://cloud.google.com/compute/docs/metadata#aggcontents
Returns:
A dictionary if the metadata server returns JSON, otherwise a string.
Raises:
http_client.HTTPException if an error corrured while
retrieving metadata.
"""
url = urlparse.urljoin(root, path)
url = _helpers._add_query_parameter(url, 'recursive', recursive)
response, content = transport.request(
http, url, headers=METADATA_HEADERS)
if response.status == http_client.OK:
decoded = _helpers._from_bytes(content)
if response['content-type'] == 'application/json':
return json.loads(decoded)
else:
return decoded
else:
raise http_client.HTTPException(
'Failed to retrieve {0} from the Google Compute Engine'
'metadata service. Response:\n{1}'.format(url, response))
示例8: test_ChunkedTransferEncodingStreamWriter_write_on_exception_still_closes
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def test_ChunkedTransferEncodingStreamWriter_write_on_exception_still_closes():
data = b'BOGUS DATA'
with mock.patch('girder_worker.docker.io.httplib.HTTPConnection', autospec=True):
s = ChunkedTransferEncodingStreamWriter('http://bogus.url.com/')
s.conn.send.side_effect = httplib.HTTPException('Bogus Exception')
with pytest.raises(httplib.HTTPException):
s.write(data)
s.conn.close.assert_called_once()
assert s._closed is True
示例9: catch_kubernetes_errors
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def catch_kubernetes_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except k8s_client.rest.ApiException as e:
if e.status == 403:
logger.exception('Permission denied')
elif e.status != 409: # Object exists or conflict in resource_version
logger.exception('Unexpected error from Kubernetes API')
return False
except (RetryFailedError, HTTPException, HTTPError, socket.error, socket.timeout):
return False
return wrapper
示例10: _do_http_request
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def _do_http_request(self, retry, machines_cache, request_executor, method, path, fields=None, **kwargs):
some_request_failed = False
for i, base_uri in enumerate(machines_cache):
if i > 0:
logger.info("Retrying on %s", base_uri)
try:
response = request_executor(method, base_uri + path, fields=fields, **kwargs)
response.data.decode('utf-8')
self._check_cluster_id(response)
if some_request_failed:
self.set_base_uri(base_uri)
self._refresh_machines_cache()
return response
except (HTTPError, HTTPException, socket.error, socket.timeout) as e:
self.http.clear()
# switch to the next etcd node because we don't know exactly what happened,
# whether the key didn't received an update or there is a network problem.
if not retry and i + 1 < len(machines_cache):
self.set_base_uri(machines_cache[i + 1])
if (isinstance(fields, dict) and fields.get("wait") == "true" and
isinstance(e, (ReadTimeoutError, ProtocolError))):
logger.debug("Watch timed out.")
raise etcd.EtcdWatchTimedOut("Watch timed out: {0}".format(e), cause=e)
logger.error("Request to server %s failed: %r", base_uri, e)
logger.info("Reconnection allowed, looking for another server.")
if not retry:
raise etcd.EtcdException('{0} {1} request failed'.format(method, path))
some_request_failed = True
raise etcd.EtcdConnectionFailed('No more machines in the cluster')
示例11: catch_consul_errors
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def catch_consul_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except (RetryFailedError, ConsulException, HTTPException, HTTPError, socket.error, socket.timeout):
return False
return wrapper
示例12: get
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def get(http, path, root=METADATA_ROOT, recursive=None):
"""Fetch a resource from the metadata server.
Args:
http: an object to be used to make HTTP requests.
path: A string indicating the resource to retrieve. For example,
'instance/service-accounts/defualt'
root: A string indicating the full path to the metadata server root.
recursive: A boolean indicating whether to do a recursive query of
metadata. See
https://cloud.google.com/compute/docs/metadata#aggcontents
Returns:
A dictionary if the metadata server returns JSON, otherwise a string.
Raises:
http_client.HTTPException if an error corrured while
retrieving metadata.
"""
url = urlparse.urljoin(root, path)
url = _helpers._add_query_parameter(url, 'recursive', recursive)
response, content = transport.request(
http, url, headers=METADATA_HEADERS)
if response.status == http_client.OK:
decoded = _helpers._from_bytes(content)
if response['content-type'] == 'application/json':
return json.loads(decoded)
else:
return decoded
else:
raise http_client.HTTPException(
'Failed to retrieve {0} from the Google Compute Engine'
'metadata service. Response:\n{1}'.format(url, response))
示例13: _Publish
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def _Publish(self, formated_samples):
try:
self._CreateDB()
body = '\n'.join(formated_samples)
self._WriteData(body)
except (IOError, httplib.HTTPException) as http_exception:
logging.error('Error connecting to the database: %s', http_exception)
示例14: __call__
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def __call__(
self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
):
"""Make an HTTP request using http.client.
Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping): Request headers.
timeout (Optional(int)): The number of seconds to wait for a
response from the server. If not specified or if None, the
socket global default timeout will be used.
kwargs: Additional arguments passed throught to the underlying
:meth:`~http.client.HTTPConnection.request` method.
Returns:
Response: The HTTP response.
Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
# socket._GLOBAL_DEFAULT_TIMEOUT is the default in http.client.
if timeout is None:
timeout = socket._GLOBAL_DEFAULT_TIMEOUT
# http.client doesn't allow None as the headers argument.
if headers is None:
headers = {}
# http.client needs the host and path parts specified separately.
parts = urllib.parse.urlsplit(url)
path = urllib.parse.urlunsplit(
("", "", parts.path, parts.query, parts.fragment)
)
if parts.scheme != "http":
raise exceptions.TransportError(
"http.client transport only supports the http scheme, {}"
"was specified".format(parts.scheme)
)
connection = http_client.HTTPConnection(parts.netloc, timeout=timeout)
try:
_LOGGER.debug("Making request: %s %s", method, url)
connection.request(method, path, body=body, headers=headers, **kwargs)
response = connection.getresponse()
return Response(response)
except (http_client.HTTPException, socket.error) as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)
finally:
connection.close()
示例15: __call__
# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import HTTPException [as 别名]
def __call__(self, url, method='GET', body=None, headers=None,
timeout=None, **kwargs):
"""Make an HTTP request using http.client.
Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping): Request headers.
timeout (Optional(int)): The number of seconds to wait for a
response from the server. If not specified or if None, the
socket global default timeout will be used.
kwargs: Additional arguments passed throught to the underlying
:meth:`~http.client.HTTPConnection.request` method.
Returns:
Response: The HTTP response.
Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
# socket._GLOBAL_DEFAULT_TIMEOUT is the default in http.client.
if timeout is None:
timeout = socket._GLOBAL_DEFAULT_TIMEOUT
# http.client doesn't allow None as the headers argument.
if headers is None:
headers = {}
# http.client needs the host and path parts specified separately.
parts = urllib.parse.urlsplit(url)
path = urllib.parse.urlunsplit(
('', '', parts.path, parts.query, parts.fragment))
if parts.scheme != 'http':
raise exceptions.TransportError(
'http.client transport only supports the http scheme, {}'
'was specified'.format(parts.scheme))
connection = http_client.HTTPConnection(parts.netloc, timeout=timeout)
try:
_LOGGER.debug('Making request: %s %s', method, url)
connection.request(
method, path, body=body, headers=headers, **kwargs)
response = connection.getresponse()
return Response(response)
except (http_client.HTTPException, socket.error) as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)
finally:
connection.close()