当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.InvalidURL方法代码示例

本文整理汇总了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
            ) 
开发者ID:apache,项目名称:airflow,代码行数:19,代码来源:test_http.py

示例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 
开发者ID:RasaHQ,项目名称:rasa_core,代码行数:18,代码来源:utils.py

示例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 
开发者ID:BradenM,项目名称:micropy-cli,代码行数:22,代码来源:helpers.py

示例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)) 
开发者ID:indico,项目名称:indico-plugins,代码行数:25,代码来源:connector.py

示例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)) 
开发者ID:weizhenzhao,项目名称:rasa_nlu,代码行数:21,代码来源:project.py

示例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)) 
开发者ID:infobloxopen,项目名称:infoblox-client,代码行数:22,代码来源:test_connector.py

示例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} 
开发者ID:liwanlei,项目名称:FXTest,代码行数:17,代码来源:PackageRequest.py

示例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} 
开发者ID:liwanlei,项目名称:FXTest,代码行数:17,代码来源:PackageRequest.py

示例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} 
开发者ID:liwanlei,项目名称:FXTest,代码行数:16,代码来源:PackageRequest.py

示例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} 
开发者ID:liwanlei,项目名称:FXTest,代码行数:17,代码来源:PackageRequest.py

示例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'] 
开发者ID:BradenM,项目名称:micropy-cli,代码行数:17,代码来源:test_utils.py

示例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') 
开发者ID:sernst,项目名称:cauldron,代码行数:9,代码来源:test_connect_command.py

示例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) 
开发者ID:DataDog,项目名称:integrations-extras,代码行数:39,代码来源:vespa.py

示例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) 
开发者ID:openstack-archive,项目名称:syntribos,代码行数:6,代码来源:test_http_checks.py

示例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 
开发者ID:open-telemetry,项目名称:opentelemetry-python,代码行数:11,代码来源:__init__.py


注:本文中的requests.exceptions.InvalidURL方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。