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


Python exceptions.SSLError方法代码示例

本文整理汇总了Python中requests.exceptions.SSLError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.SSLError方法的具体用法?Python exceptions.SSLError怎么用?Python exceptions.SSLError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在requests.exceptions的用法示例。


在下文中一共展示了exceptions.SSLError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_do_api_call_succeeds_after_retrying

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def test_do_api_call_succeeds_after_retrying(self):
        for exception in [requests_exceptions.ConnectionError,
                          requests_exceptions.SSLError,
                          requests_exceptions.Timeout,
                          requests_exceptions.ConnectTimeout,
                          requests_exceptions.HTTPError]:
            with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
                with mock.patch.object(self.hook.log, 'error') as mock_errors:
                    setup_mock_requests(
                        mock_requests,
                        exception,
                        error_count=2,
                        response_content={'run_id': '1'}
                    )

                    response = self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})

                    self.assertEqual(mock_errors.call_count, 2)
                    self.assertEqual(response, {'run_id': '1'}) 
开发者ID:apache,项目名称:airflow,代码行数:21,代码来源:test_databricks.py

示例2: test_do_api_call_waits_between_retries

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def test_do_api_call_waits_between_retries(self, mock_sleep):
        retry_delay = 5
        self.hook = DatabricksHook(retry_delay=retry_delay)

        for exception in [requests_exceptions.ConnectionError,
                          requests_exceptions.SSLError,
                          requests_exceptions.Timeout,
                          requests_exceptions.ConnectTimeout,
                          requests_exceptions.HTTPError]:
            with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
                with mock.patch.object(self.hook.log, 'error'):
                    mock_sleep.reset_mock()
                    setup_mock_requests(mock_requests, exception)

                    with self.assertRaises(AirflowException):
                        self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})

                    self.assertEqual(len(mock_sleep.mock_calls), self.hook.retry_limit - 1)
                    calls = [
                        mock.call(retry_delay),
                        mock.call(retry_delay)
                    ]
                    mock_sleep.assert_has_calls(calls) 
开发者ID:apache,项目名称:airflow,代码行数:25,代码来源:test_databricks.py

示例3: handle_connection_errors

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def handle_connection_errors(client):
    try:
        yield
    except SSLError as e:
        log.error('SSL error: %s' % e)
        raise ConnectionError()
    except RequestsConnectionError as e:
        if e.args and isinstance(e.args[0], ReadTimeoutError):
            log_timeout_error(client.timeout)
            raise ConnectionError()
        exit_with_error(get_conn_error_message(client.base_url))
    except APIError as e:
        log_api_error(e, client.api_version)
        raise ConnectionError()
    except (ReadTimeout, socket.timeout):
        log_timeout_error(client.timeout)
        raise ConnectionError()
    except Exception as e:
        if is_windows():
            import pywintypes
            if isinstance(e, pywintypes.error):
                log_windows_pipe_error(e)
                raise ConnectionError()
        raise 
开发者ID:QData,项目名称:deepWordBug,代码行数:26,代码来源:errors.py

示例4: test_is_docker_image_already_in_registry_http_when_image_does_not_exist

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def test_is_docker_image_already_in_registry_http_when_image_does_not_exist(
    mock_read_docker_registry_creds, mock_request_head, mock_get_service_docker_registry
):
    def mock_head(session, url, timeout):
        if url.startswith("https"):
            raise SSLError("Uh oh")
        return MagicMock(status_code=404)

    mock_get_service_docker_registry.return_value = "registry"
    mock_request_head.side_effect = mock_head

    mock_read_docker_registry_creds.return_value = (None, None)
    assert not is_docker_image_already_in_registry(
        "fake_service", "fake_soa_dir", "fake_sha"
    )
    mock_request_head.assert_called_with(
        ANY,
        "http://registry/v2/services-fake_service/manifests/paasta-fake_sha",
        timeout=30,
    ) 
开发者ID:Yelp,项目名称:paasta,代码行数:22,代码来源:test_cmds_push_to_registry.py

示例5: test_neutron_exception_is_raised_on_any_request_error

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [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

示例6: initWithAdapter_

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def initWithAdapter_(self, adapter):
        self = objc.super(NSURLSessionAdapterDelegate, self).init()

        if self is None:
            return None

        self.adapter = adapter
        self.bytesReceived = 0
        self.expectedLength = -1
        self.percentComplete = 0
        self.done = False
        self.error = None
        self.SSLError = None
        self.output = NSMutableData.dataWithCapacity_(1024)
        self.status = None
        self.headers = {}
        self.verify = True
        self.credential = None
        self.history = []

        return self 
开发者ID:jssimporter,项目名称:python-jss,代码行数:23,代码来源:nsurlsession_adapter.py

示例7: URLSession_task_didCompleteWithError_

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def URLSession_task_didCompleteWithError_(
            self,
            session,    # type: NSURLSession
            task,       # type: NSURLSessionTask
            error       # type: NSError
    ):  # type: (...) -> None
        logger.debug('URLSession_task_didCompleteWithError_')
        if error:
            self.error = error
            # If this was an SSL error, try to extract the SSL error code.
            if 'NSUnderlyingError' in error.userInfo():
                ssl_code = error.userInfo()['NSUnderlyingError'].userInfo().get(
                    '_kCFNetworkCFStreamSSLErrorOriginalValue', None)
                if ssl_code:
                    self.SSLError = (ssl_code, ssl_error_codes.get(
                        ssl_code, 'Unknown SSL error'))
        else:
            logger.debug('no error(s)')

        self.done = True 
开发者ID:jssimporter,项目名称:python-jss,代码行数:22,代码来源:nsurlsession_adapter.py

示例8: server_status

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def server_status(connection, verbose=False):
    """
     Args:
        connection: MicroStrategy REST API connection object
        verbose (bool, optional): Verbosity of server responses; defaults to False.
    Returns:
        Complete HTTP response object
    """

    try:
        response = connection.session.get(url=connection.base_url + '/api/status')
    except SSLError:
        exception_handler("SSL certificate error, if you are using a self-signed certificate, copy your SSL certificate to your working directory or pass the path to the certificate to your Connection. \nOtherwise please double check that the link you are using comes from a trusted source.\n\nCheck readme for more details.",  # noqa
                          SSLError)

    if verbose:
        print(response.url)
    if not response.ok:
        response_handler(response, "Failed to check server status")
    return response 
开发者ID:MicroStrategy,项目名称:mstrio-py,代码行数:22,代码来源:misc.py

示例9: test_make_request

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def test_make_request(self, *args, **kvargs):
        headers = {}
        params = {'method': 'GET',
                  'service': 'ec2',
                  'region': 'region',
                  'uri': 'https://user:pass@host:123/path/?a=b&c=d',
                  'headers': headers,
                  'data': '',
                  'access_key': '',
                  'secret_key': '',
                  'security_token': '',
                  'data_binary': False,
                  'verify': False}

        with pytest.raises(SSLError):
            make_request(**params)

        pass 
开发者ID:okigan,项目名称:awscurl,代码行数:20,代码来源:unit_test.py

示例10: run_query

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def run_query(self):
        q = 'select * from weather.forecast where woeid=%s' % self.woeid
        url = 'https://query.yahooapis.com/v1/yql?q=%s' % q
        params = {}
        params['format'] = 'json'
        try:
            ans = requests.get(url, auth=self.oauth, params=params)
        except SSLError as e:
            '''
            Bug #1568774
            '''
            print('wyahooapi.py: Bug #1568774', str(e))
            print('wyahooapi.py: Unable to query https url, switch to http url')
            url = 'http://query.yahooapis.com/v1/yql?q=%s' % q
            ans = requests.get(url, auth=self.oauth, params=params)

        if ans.status_code == 200:
            return ans.json()
        else:
            print('wyahooapi.py: Request status code not 200, status_code = ', str(ans.status_code))
            return None 
开发者ID:atareao,项目名称:my-weather-indicator,代码行数:23,代码来源:wyahooapi.py

示例11: _has_api

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def _has_api(url: str) -> bool:
    if urlparse(url).hostname in ('pypi.org', 'python.org', 'test.pypi.org'):
        return True
    full_url = urljoin(url, 'dephell/json/')
    try:
        response = requests.head(full_url)
    except (SSLError, ConnectionError):
        return False
    return response.status_code < 400 
开发者ID:dephell,项目名称:dephell,代码行数:11,代码来源:_repos.py

示例12: renew_token

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def renew_token(self, token):
        """Renew expired ThreatConnect Token.

        This method will renew a token and update the token_map with new token and expiration.

        Args:
            token (str): The ThreatConnect API token.
            token_expires (int): The token expiration timestamp.
        """
        api_token_data = {}
        self.log.in_token_renewal = True  # pause API logging

        # log token information
        try:
            params = {'expiredToken': token}
            url = f'{self.token_url}/appAuth'
            r = self.session.get(url, params=params, verify=self.verify)

            if not r.ok:
                err_reason = r.text or r.reason
                err_msg = (
                    f'Token Retry Error. API status code: {r.status_code}, '
                    f'API message: {err_reason}, '
                    f'Token: {self.printable_token(token)}.'
                )
                self.log.error(err_msg)
                raise RuntimeError(1042, err_msg)
        except exceptions.SSLError:  # pragma: no cover
            raise RuntimeError('Token renewal failed with an SSL Error.')

        # process response for token
        try:
            api_token_data = r.json()
        except (AttributeError, ValueError) as e:  # pragma: no cover
            raise RuntimeError(f'Token renewal failed ({e}).')
        finally:
            self.log.in_token_renewal = False

        return api_token_data 
开发者ID:ThreatConnect-Inc,项目名称:tcex,代码行数:41,代码来源:tokens.py

示例13: _do

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def _do(self, f, relative_url, *args, **kwargs):
        kwargs['auth'] = self.auth
        kwargs['verify'] = not self.insecure
        if self._fallback:
            try:
                res = f(self._base + relative_url, *args, **kwargs)
                self._fallback = None  # don't fallback after one success
                return res
            except (SSLError, requests.ConnectionError):
                self._base = self._fallback
                self._fallback = None
        return f(self._base + relative_url, *args, **kwargs) 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:14,代码来源:util.py

示例14: test_do_api_call_retries_with_retryable_error

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def test_do_api_call_retries_with_retryable_error(self):
        for exception in [requests_exceptions.ConnectionError,
                          requests_exceptions.SSLError,
                          requests_exceptions.Timeout,
                          requests_exceptions.ConnectTimeout,
                          requests_exceptions.HTTPError]:
            with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
                with mock.patch.object(self.hook.log, 'error') as mock_errors:
                    setup_mock_requests(mock_requests, exception)

                    with self.assertRaises(AirflowException):
                        self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})

                    self.assertEqual(mock_errors.call_count, self.hook.retry_limit) 
开发者ID:apache,项目名称:airflow,代码行数:16,代码来源:test_databricks.py

示例15: QA_fetch_huobi_symbols

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import SSLError [as 别名]
def QA_fetch_huobi_symbols():
    """
    Get Symbol and currencies
    """
    url = urljoin(Huobi_base_url, "/v1/common/symbols")
    retries = 1
    datas = list()
    while (retries != 0):
        try:
            req = requests.get(url, timeout=TIMEOUT)
            retries = 0
        except (ConnectTimeout, ConnectionError, SSLError, ReadTimeout):
            retries = retries + 1
            if (retries % 6 == 0):
                print(ILOVECHINA)
            print("Retry get_exchange_info #{}".format(retries - 1))
            time.sleep(0.5)
    if (retries == 0):
        msg_dict = json.loads(req.content)
        if (('status' in msg_dict) and (msg_dict['status'] == 'ok')
                and ('data' in msg_dict)):
            if len(msg_dict["data"]) == 0:
                return []
            for symbol in msg_dict["data"]:
                # 只导入上架交易对
                if (symbol['state'] == 'online'):
                    datas.append(symbol)

    return datas 
开发者ID:QUANTAXIS,项目名称:QUANTAXIS,代码行数:31,代码来源:QAhuobi.py


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