本文整理匯總了Python中requests.exceptions.InvalidURL方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.InvalidURL方法的具體用法?Python exceptions.InvalidURL怎麽用?Python exceptions.InvalidURL使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類requests.exceptions
的用法示例。
在下文中一共展示了exceptions.InvalidURL方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_hook_with_method_in_lowercase
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def test_hook_with_method_in_lowercase(self, mock_requests, request_mock):
from requests.exceptions import MissingSchema, InvalidURL
with mock.patch(
'airflow.hooks.base_hook.BaseHook.get_connection',
side_effect=get_airflow_connection_with_port
):
data = "test params"
try:
self.get_lowercase_hook.run('v1/test', data=data)
except (MissingSchema, InvalidURL):
pass
request_mock.assert_called_once_with(
mock.ANY,
mock.ANY,
headers=mock.ANY,
params=data
)
示例2: download_file_from_url
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def download_file_from_url(url: Text) -> Text:
"""Download a story file from a url and persists it into a temp file.
Returns the file path of the temp file that contains the
downloaded content."""
from rasa_nlu import utils as nlu_utils
if not nlu_utils.is_url(url):
raise InvalidURL(url)
async with aiohttp.ClientSession() as session:
async with session.get(url, raise_for_status=True) as resp:
filename = nlu_utils.create_temporary_file(await resp.read(),
mode="w+b")
return filename
示例3: ensure_valid_url
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def ensure_valid_url(url):
"""Ensure a url is valid.
Args:
url (str): URL to validate
Raises:
InvalidURL: URL is not a valid url
ConnectionError: Failed to connect to url
HTTPError: Reponse was not 200 <OK>
Returns:
str: valid url
"""
if not is_url(url):
raise reqexc.InvalidURL(f"{url} is not a valid url!")
resp = requests.head(url, allow_redirects=True)
resp.raise_for_status()
return url
示例4: _validate_server_url
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def _validate_server_url(self):
"""Validates self.server_url"""
try:
request = requests.head(self.server_url)
if request.status_code >= 400:
raise InvenioConnectorServerError(
"Unexpected status code '%d' accessing URL: %s"
% (request.status_code, self.server_url))
except (InvalidSchema, MissingSchema) as err:
raise InvenioConnectorServerError(
"Bad schema, expecting http:// or https://:\n %s" % (err,))
except ConnectionError as err:
raise InvenioConnectorServerError(
"Couldn't establish connection to '%s':\n %s"
% (self.server_url, err))
except InvalidURL as err:
raise InvenioConnectorServerError(
"Invalid URL '%s':\n %s"
% (self.server_url, err))
except RequestException as err:
raise InvenioConnectorServerError(
"Unknown error connecting to '%s':\n %s"
% (self.server_url, err))
示例5: _update_model_from_server
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def _update_model_from_server(model_server: EndpointConfig,
project: 'Project') -> None:
"""Load a zipped Rasa NLU model from a URL and update the passed
project."""
if not is_url(model_server.url):
raise InvalidURL(model_server)
model_directory = tempfile.mkdtemp()
new_model_fingerprint, filename = _pull_model_and_fingerprint(
model_server, model_directory, project.fingerprint)
if new_model_fingerprint:
model_name = _get_remote_model_name(filename)
project.fingerprint = new_model_fingerprint
project.update_model_from_dir_and_unload_others(model_directory,
model_name)
else:
logger.debug("No new model found at URL {}".format(model_server.url))
示例6: test_neutron_exception_is_raised_on_any_request_error
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def test_neutron_exception_is_raised_on_any_request_error(self):
# timeout exception raises InfobloxTimeoutError
f = mock.Mock()
f.__name__ = 'mock'
f.side_effect = req_exc.Timeout
self.assertRaises(exceptions.InfobloxTimeoutError,
connector.reraise_neutron_exception(f))
# all other request exception raises InfobloxConnectionError
supported_exceptions = [req_exc.HTTPError,
req_exc.ConnectionError,
req_exc.ProxyError,
req_exc.SSLError,
req_exc.TooManyRedirects,
req_exc.InvalidURL]
for ex in supported_exceptions:
f.side_effect = ex
self.assertRaises(exceptions.InfobloxConnectionError,
connector.reraise_neutron_exception(f))
示例7: get
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def get(self, url,headers,parms):#get消息
try:
self.r = requests.get(url, headers=headers,params=parms,timeout=Interface_Time_Out)
self.r.encoding = 'UTF-8'
spend=self.r.elapsed.total_seconds()
json_response = json.loads(self.r.text)
return json_response,spend
except exceptions.Timeout :
return {'get請求出錯': "請求超時" }
except exceptions.InvalidURL:
return {'get請求出錯': "非法url"}
except exceptions.HTTPError:
return {'get請求出錯': "http請求錯誤"}
except Exception as e:
return {'get請求出錯':"錯誤原因:%s"%e}
示例8: post
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def post(self, url, params,headers):#post消息
data = json.dumps(params)
try:
self.r =requests.post(url,params=data,headers=headers,timeout=Interface_Time_Out)
json_response = json.loads(self.r.text)
spend=self.r.elapsed.total_seconds()
return json_response,spend
except exceptions.Timeout :
return {'post請求出錯': "請求超時" }
except exceptions.InvalidURL:
return {'post請求出錯': "非法url"}
except exceptions.HTTPError:
return {'post請求出錯': "http請求錯誤"}
except Exception as e:
return {'post請求出錯': "錯誤原因:%s" % e}
示例9: delfile
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def delfile(self,url,params,headers):#刪除的請求
try:
self.rdel_word=requests.delete(url,data=params,headers=headers,timeout=Interface_Time_Out)
json_response=json.loads(self.rdel_word.text)
spend=self.rdel_word.elapsed.total_seconds()
return json_response,spend
except exceptions.Timeout :
return {'delete請求出錯': "請求超時" }
except exceptions.InvalidURL:
return {'delete請求出錯': "非法url"}
except exceptions.HTTPError:
return {'delete請求出錯': "http請求錯誤"}
except Exception as e:
return {'delete請求出錯': "錯誤原因:%s" % e}
示例10: putfile
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def putfile(self,url,params,headers):#put請求
try:
self.rdata=json.dumps(params)
me=requests.put(url,self.rdata,headers=headers,timeout=Interface_Time_Out)
json_response=json.loads(me.text)
spend=me.elapsed.total_seconds()
return json_response,spend
except exceptions.Timeout :
return {'put請求出錯': "請求超時" }
except exceptions.InvalidURL:
return {'put請求出錯': "非法url"}
except exceptions.HTTPError:
return {'put請求出錯': "http請求錯誤"}
except Exception as e:
return {'put請求出錯': "錯誤原因:%s" % e}
示例11: test_ensure_valid_url
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def test_ensure_valid_url(mocker, test_urls):
"""should ensure url is valid"""
u = test_urls
with pytest.raises(InvalidURL):
utils.ensure_valid_url(test_urls['invalid'])
with pytest.raises(ConnectionError):
mocker.patch.object(utils, "is_url", return_value=True)
mock_head = mocker.patch.object(requests, "head")
mock_head.side_effect = [ConnectionError]
utils.ensure_valid_url(u['valid'])
mocker.stopall()
with pytest.raises(HTTPError):
utils.ensure_valid_url(u['bad_resp'])
result = utils.ensure_valid_url(u['valid'])
assert result == u['valid']
示例12: test_invalid_url_error
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def test_invalid_url_error(self, requests_get: MagicMock):
"""Should fail if the url is not valid."""
requests_get.side_effect = request_exceptions.InvalidURL('Fake')
r = support.run_command('connect "a url"')
self.assert_has_error_code(r, 'INVALID_URL')
示例13: check
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def check(self, instance):
self.metric_count = 0
self.services_up = 0
instance_tags = instance.get('tags', [])
consumer = instance.get('consumer')
if not consumer:
raise CheckException("The consumer must be specified in the configuration.")
url = self.URL + '?consumer=' + consumer
try:
json = self._get_metrics_json(url)
if 'services' not in json:
self.service_check(self.METRICS_SERVICE_CHECK, AgentCheck.WARNING, tags=instance_tags,
message="No services in response from metrics proxy on {}".format(url))
return
for service in json['services']:
service_name = service['name']
self._report_service_status(instance_tags, service_name, service)
for metrics in service['metrics']:
self._emit_metrics(service_name, metrics, instance_tags)
self.log.info("Forwarded %s metrics to hq for %s services", self.metric_count, self.services_up)
self.service_check(self.METRICS_SERVICE_CHECK, AgentCheck.OK, tags=instance_tags,
message="Metrics collected successfully for consumer {}".format(consumer))
except Timeout as e:
self._report_metrics_error("Timed out connecting to Vespa's node metrics api: {}".format(e),
AgentCheck.CRITICAL, instance_tags)
except (HTTPError, InvalidURL, ConnectionError) as e:
self._report_metrics_error("Could not connect to Vespa's node metrics api: {}".format(e),
AgentCheck.CRITICAL, instance_tags)
except JSONDecodeError as e:
self._report_metrics_error("Error parsing JSON from Vespa's node metrics api: {}".format(e),
AgentCheck.CRITICAL, instance_tags)
except Exception as e:
self._report_metrics_error("Unexpected error: {}".format(e),
AgentCheck.WARNING, instance_tags)
示例14: test_invalid_url
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def test_invalid_url(self):
signal = http_checks.check_fail(rex.InvalidURL())
self._assert_has_tags(self.bad_request_tags, signal)
self._assert_has_slug("HTTP_FAIL_INVALID_URL", signal)
示例15: _exception_to_canonical_code
# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import InvalidURL [as 別名]
def _exception_to_canonical_code(exc: Exception) -> StatusCanonicalCode:
if isinstance(
exc,
(InvalidURL, InvalidSchema, MissingSchema, URLRequired, ValueError),
):
return StatusCanonicalCode.INVALID_ARGUMENT
if isinstance(exc, Timeout):
return StatusCanonicalCode.DEADLINE_EXCEEDED
return StatusCanonicalCode.UNKNOWN