本文整理汇总了Python中six.moves.urllib.error.HTTPError方法的典型用法代码示例。如果您正苦于以下问题:Python error.HTTPError方法的具体用法?Python error.HTTPError怎么用?Python error.HTTPError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.urllib.error
的用法示例。
在下文中一共展示了error.HTTPError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: provisioning_completed
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def provisioning_completed(self):
"""Signal to Packet that the instance is ready.
To complete the provisioning, on the first boot after installation
make a GET request to CONF.packet.metadata_url, which will return a
JSON object which contains phone_home_url entry.
Make a POST request to phone_home_url with no body (important!)
and this will complete the installation process.
"""
phone_home_url = self._get_phone_home_url()
LOG.info("Calling home to: %s", phone_home_url)
try:
action = lambda: self._http_request(url=phone_home_url,
method="post")
return self._exec_with_retry(action)
except error.HTTPError as exc:
LOG.exception(exc)
raise exception.MetadataEndpointException(
"Failed to call home to the metadata service")
示例2: _test_post_password
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def _test_post_password(self, mock_http_request,
mock_get_phone_url, mock_sleep, fail=False):
fake_phone_url = 'fake_phone_url'
fake_response = 'fake_response'
fake_encoded_password = b'fake_password'
if fail:
mock_http_request.side_effect = (
error.HTTPError(401, "invalid", {}, 0, 0))
with self.assertRaises(exception.MetadataEndpointException):
self._packet_service.post_password(fake_encoded_password)
else:
mock_http_request.return_value = fake_response
mock_get_phone_url.return_value = fake_phone_url
response = self._packet_service.post_password(
fake_encoded_password)
mock_get_phone_url.assert_called_once()
mock_http_request.assert_called_once_with(
data='{"password": "fake_password"}',
url=fake_phone_url)
self.assertEqual(response, fake_response)
示例3: _test_provisioning_completed
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def _test_provisioning_completed(self, mock_http_request,
mock_get_phone_url, mock_sleep,
fail=False):
fake_phone_url = 'fake_phone_url'
fake_response = 'fake_response'
if fail:
mock_http_request.side_effect = (
error.HTTPError(401, "invalid", {}, 0, 0))
with self.assertRaises(exception.MetadataEndpointException):
self._packet_service.provisioning_completed()
else:
mock_http_request.return_value = fake_response
mock_get_phone_url.return_value = fake_phone_url
response = self._packet_service.provisioning_completed()
mock_get_phone_url.assert_called_once()
mock_http_request.assert_called_once_with(
url=fake_phone_url,
method="post")
self.assertEqual(response, fake_response)
示例4: download
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def download(self):
"""Downloads the archive from one of the mirrors"""
if not os.path.exists(self.archive_path):
for turn in xrange(self.trials_404):
for i, link in enumerate(self.download_links()):
try:
return self.do_download(link, self.archive_path)
except HTTPError as e:
if e.code != 404:
raise
print("HTTP 404 while trying to get the archive using link" \
" '%s' (trial %d/%d)" % (link, turn+1, self.trials_404))
except URLError as e:
print("Error while trying to get the archive using link" \
" '%s' (trial %d/%d)" % (link, turn+1, self.trials_404))
raise e
示例5: check_url
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def check_url(docker_ip, public_port):
"""Check if a service is reachable.
Makes a simple GET request to '/' of the HTTP endpoint. Service is
available if returned status code is < 500.
"""
url = 'http://{}:{}'.format(docker_ip, public_port)
try:
r = urlopen(url)
return r.code < 500
except HTTPError as e:
# If service returns e.g. a 404 it's ok
return e.code < 500
except Exception:
# Possible service not yet started
return False
示例6: _request
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def _request(self, req_body=None, method=None,
header=constants.CONTENT_TYPE_URLENCODE):
req = url_request.Request(self._url, req_body.encode(), header)
if method not in (None, 'GET', 'POST'):
req.get_method = lambda: method
self._http_log_req(req)
try:
resp = self.url_opener.open(req)
resp_body = resp.read()
self._http_log_resp(resp, resp_body)
except url_error.HTTPError as http_err:
if '403' == six.text_type(http_err.code):
raise exception.NotAuthorized()
else:
err = {'errorCode': -1,
'httpStatusCode': http_err.code,
'messages': six.text_type(http_err),
'request': req_body}
msg = (_("The request is invalid. Reason: %(reason)s") %
{'reason': err})
raise exception.ManilaException(message=msg)
return resp_body
示例7: test_upload_vnf_package_from_uri_with_invalid_auth
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def test_upload_vnf_package_from_uri_with_invalid_auth(self,
mock_url_open):
address_information = "http://localhost/test.zip"
user_name = "username"
password = "password"
mock_url_open.side_effect = urlerr.HTTPError(
url='', code=401, msg='HTTP Error 401 Unauthorized', hdrs={},
fp=None)
self.assertRaises(exceptions.VNFPackageURLInvalid,
self.conductor.upload_vnf_package_from_uri,
self.context,
self.vnf_package,
address_information,
user_name=user_name,
password=password)
self.assertEqual('CREATED', self.vnf_package.onboarding_state)
示例8: get
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def get(path, **kwargs):
"""Send a GET request.
Parameters
----------
path : str
The path portion of the URL.
kwargs : any
Passed to `request`.
Returns
-------
RestObj or None
The results or None if the resource was not found.
"""
try:
return request('get', path, **kwargs)
except HTTPError as e:
if e.code == 404:
return None # Resource not found
raise e
示例9: test_register_model_403_error
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def test_register_model_403_error(get_project, get_repository):
"""Verify HTTP 403 is converted to a user-friendly error.
Depending on environment configuration, this can happen when attempting to
find a repository.
See: https://github.com/sassoftware/python-sasctl/issues/39
"""
from six.moves.urllib.error import HTTPError
from sasctl.exceptions import AuthorizationError
from sasctl.tasks import register_model
get_project.return_value = {'name': 'Project Name'}
get_repository.side_effect = HTTPError(None, 403, None, None, None)
# HTTP 403 error when getting repository should throw a user-friendly
# AuthorizationError
with pytest.raises(AuthorizationError):
register_model(None, 'model name', 'project name')
# All other errors should be bubbled up
get_repository.side_effect = HTTPError(None, 404, None, None, None)
with pytest.raises(HTTPError):
register_model(None, 'model name', 'project name')
示例10: FetchDiscoveryDoc
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def FetchDiscoveryDoc(discovery_url, retries=5):
"""Fetch the discovery document at the given url."""
discovery_urls = _NormalizeDiscoveryUrls(discovery_url)
discovery_doc = None
last_exception = None
for url in discovery_urls:
for _ in range(retries):
try:
content = _GetURLContent(url)
if isinstance(content, bytes):
content = content.decode('utf8')
discovery_doc = json.loads(content)
if discovery_doc:
return discovery_doc
except (urllib_error.HTTPError, urllib_error.URLError) as e:
logging.info(
'Attempting to fetch discovery doc again after "%s"', e)
last_exception = e
if discovery_doc is None:
raise CommunicationError(
'Could not find discovery doc at any of %s: %s' % (
discovery_urls, last_exception))
示例11: test_app_http_error_retry_ok
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def test_app_http_error_retry_ok(self, urlopen_mock):
http_error = HTTPError(
"http://mock.test",
500,
"HTTP 500 whatever",
None,
None
)
# this will make the function raise exception / return the value
# in this given order
side_effect_results = [
http_error,
http_error,
open(TestEsiApp.ESI_META_SWAGGER)
]
urlopen_mock.side_effect = side_effect_results
with httmock.HTTMock(*_swagger_spec_mock_):
EsiApp(cache_prefix='esipy_test')
self.assertEqual(urlopen_mock.call_count, 3)
示例12: create_HTTPError
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def create_HTTPError(url=Undefined, code=Undefined, msg=Undefined,
hdrs=Undefined, fp=None):
"""
Test utility method constructing a HTTPError instance. Allows callers
to construct a HTTPError instance using input data they are interested
in, with some built-in default values used for any input data they are
not interested in.
"""
if url is Undefined:
url = object()
if code is Undefined:
code = object()
if msg is Undefined:
msg = object()
if hdrs is Undefined:
hdrs = object()
return HTTPError(url=url, code=code, msg=msg, hdrs=hdrs, fp=fp)
示例13: test_open_propagating_HTTPError_exceptions
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def test_open_propagating_HTTPError_exceptions(self, status_code,
monkeypatch):
"""
HttpTransport open() operation should transform HTTPError urlopener
exceptions to suds.transport.TransportError exceptions.
"""
# Setup.
monkeypatch.delattr(locals(), "e", False)
fp = MockFP()
e_original = self.create_HTTPError(code=status_code, fp=fp)
t = suds.transport.http.HttpTransport()
t.urlopener = MockURLOpenerSaboteur(open_exception=e_original)
request = create_request()
# Execute.
e = pytest.raises(suds.transport.TransportError, t.open, request).value
try:
# Verify.
assert e.args == (str(e_original),)
assert e.httpcode is status_code
assert e.fp is fp
finally:
del e # explicitly break circular reference chain in Python 3
示例14: test_operation_invoke_with_urlopen_accept_no_content__data
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def test_operation_invoke_with_urlopen_accept_no_content__data(self,
status_code):
"""
suds.client.Client web service operation invocation expecting output
data, and for which a corresponding urlopen call raises a HTTPError
with status code ACCEPTED or NO_CONTENT, should report this as a
TransportError.
"""
e = self.create_HTTPError(code=status_code)
transport = suds.transport.http.HttpTransport()
transport.urlopener = MockURLOpenerSaboteur(open_exception=e)
wsdl = testutils.wsdl('<xsd:element name="o" type="xsd:string"/>',
output="o", operation_name="f")
client = testutils.client_from_wsdl(wsdl, transport=transport)
pytest.raises(suds.transport.TransportError, client.service.f)
示例15: test_operation_invoke_with_urlopen_accept_no_content__no_data
# 需要导入模块: from six.moves.urllib import error [as 别名]
# 或者: from six.moves.urllib.error import HTTPError [as 别名]
def test_operation_invoke_with_urlopen_accept_no_content__no_data(self,
status_code):
"""
suds.client.Client web service operation invocation expecting no output
data, and for which a corresponding urlopen call raises a HTTPError
with status code ACCEPTED or NO_CONTENT, should treat this as a
successful invocation.
"""
# We are not yet sure that the behaviour checked for in this test is
# actually desired. The test is only an 'educated guess' prepared to
# demonstrate a related problem in the original suds library
# implementation. The original implementation is definitely buggy as
# its web service operation invocation raises an AttributeError
# exception by attempting to access a non-existing 'None.message'
# attribute internally.
e = self.create_HTTPError(code=status_code)
transport = suds.transport.http.HttpTransport()
transport.urlopener = MockURLOpenerSaboteur(open_exception=e)
wsdl = testutils.wsdl('<xsd:element name="o" type="xsd:string"/>',
output="o", operation_name="f")
client = testutils.client_from_wsdl(wsdl, transport=transport)
assert client.service.f() is None