Python requests.exceptions.SSLError() Examples

The following are 30 code examples of requests.exceptions.SSLError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests.exceptions , or try the search function .
Example #1
Source File: test_databricks.py    From airflow with Apache License 2.0 7 votes vote down vote up
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) 
Example #2
Source File: test_connector.py    From infoblox-client with Apache License 2.0 7 votes vote down vote up
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)) 
Example #3
Source File: nsurlsession_adapter.py    From python-jss with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: nsurlsession_adapter.py    From python-jss with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: test_databricks.py    From airflow with Apache License 2.0 6 votes vote down vote up
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'}) 
Example #6
Source File: test_cmds_push_to_registry.py    From paasta with Apache License 2.0 6 votes vote down vote up
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,
    ) 
Example #7
Source File: misc.py    From mstrio-py with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: wyahooapi.py    From my-weather-indicator with MIT License 6 votes vote down vote up
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 
Example #9
Source File: unit_test.py    From awscurl with MIT License 6 votes vote down vote up
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 
Example #10
Source File: test_wildcard_cert_nohttps.py    From nginx-proxy with MIT License 5 votes vote down vote up
def test_web3_https_is_500_and_SSL_validation_fails(docker_compose, nginxproxy):
    with pytest.raises( (CertificateError, SSLError) ) as excinfo:
        nginxproxy.get("https://3.web.nginx-proxy.tld/port")
    assert """hostname '3.web.nginx-proxy.tld' doesn't match 'nginx-proxy.tld'""" in str(excinfo.value)

    r = nginxproxy.get("https://3.web.nginx-proxy.tld/port", verify=False)
    assert r.status_code == 500 
Example #11
Source File: virtualhost.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def fingerprint_virtual_host(
        self,
        org_uuid=None,
        network_service_uuid=None,
        network_service_scan_uuid=None,
        use_ssl=None,
        hostname=None,
        order_uuid=None,
):
    """
    Get a virtual host fingerprint from the web service running at the given network service for
    the given hostname.
    :param org_uuid: The UUID of the organization to retrieve a fingerprint for.
    :param network_service_uuid: The UUID of the network service where the web service resides.
    :param network_service_scan_uuid: The UUID of the network service scan that this fingerprinting is a part
    of.
    :param use_ssl: Whether or not to use SSL to connect to the remote endpoint.
    :param hostname: The hostname to submit a request for.
    :return: None
    """
    logger.info(
        "Now retrieving virtual host fingerprint for service %s with hostname %s. Organization is %s."
        % (network_service_uuid, hostname, org_uuid)
    )
    ip_address, port, protocol = self.get_endpoint_information()
    inspector = WebServiceInspector(ip_address=ip_address, port=port, use_ssl=use_ssl, hostname=hostname)
    try:
        response = inspector.get()
    except (SSLError, ReadTimeout) as e:
        logger.error(
            "Error thrown when retrieving fingerprint: %s %s."
            % (e.__class__.__name__, e.message)
        )
        return
    logger.info(
        "Fingerprint retrieved for virtual host %s on service %s."
        % (hostname, network_service_uuid)
    )
    fingerprint_model = response.to_es_model(model_uuid=network_service_scan_uuid, db_session=self.db_session)
    fingerprint_model.save(org_uuid)
    logger.info("Fingerprint pushed to Elasticsearch successfully.") 
Example #12
Source File: error_handler.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def error_handler(excp):
    if excp.type is SSLError:
        print """
            SSL Error: Please check your certificates or read our wiki for further info:
            https://github.com/pixelated-project/pixelated-user-agent/wiki/Configuring-and-using-SSL-Certificates-for-LEAP-provider
            Error reference: %s
            """ % excp.getErrorMessage()
    else:
        raise excp 
Example #13
Source File: text_analytics.py    From bot with GNU General Public License v3.0 5 votes vote down vote up
def detect_language(text):
    """
    Detect the language of the specified text

    :return:
        String with the language of text or None
    """

    POST = "/api/{}/tr.json/detect?key={}&text={}".format(
        YANDEX_API_VERSION, YANDEX_CONFIG["API_key"], text
    )
    logger = Settings.logger

    try:
        req = requests.get(YANDEX_HOST + POST)
    except SSLError as exc:
        print("")
        logger.exception(
            "{}\t~there was a connection error :<"
            "\n{}\n".format(YANDEX_FAILURE_MSG, str(exc).encode("utf-8"))
        )
        return None

    data = json.loads(req.text)
    # check if there are any errors in the request
    request_state = lift_yandex_request(data)
    if request_state is not True:
        return None

    # get the result
    if "lang" in data.keys() and data["lang"]:
        language_of_text = data["lang"]
        return language_of_text

    else:
        return None 
Example #14
Source File: text_analytics.py    From bot with GNU General Public License v3.0 5 votes vote down vote up
def yandex_supported_languages(language_code="en"):
    """
    Get the list of translation directions supported by the service
    Overview of supported langugages:
        https://tech.yandex.com/translate/doc/dg/concepts/api-overview
        -docpage/#api-overview__languages

    :return:
        dict.keys() object containing language codes or None
    """

    POST = "/api/{}/tr.json/getLangs?key={}&ui={}".format(
        YANDEX_API_VERSION, YANDEX_CONFIG["API_key"], language_code
    )
    logger = Settings.logger

    try:
        req = requests.get(YANDEX_HOST + POST)
    except SSLError:
        # try again one more time
        sleep(2)

        try:
            req = requests.get(YANDEX_HOST + POST)
        except SSLError as exc:
            print("")
            logger.exception(
                "{}\t~there was a connection error :<"
                "\n{}\n".format(YANDEX_FAILURE_MSG, str(exc).encode("utf-8"))
            )
            return None

    data = json.loads(req.text)
    if "langs" in data.keys() and data["langs"]:
        language_codes = data["langs"].keys()
        return language_codes

    else:
        return None 
Example #15
Source File: exceptions.py    From labkey-api-python with Apache License 2.0 5 votes vote down vote up
def _get_message(server_context, e):
        switcher = {
            exceptions.ConnectionError:
                'Failed to connect to server. Ensure the server_context domain, context_path, '
                'and SSL are configured correctly.',
            exceptions.InvalidURL:
                'Failed to parse URL. Context is ' + str(server_context),
            exceptions.SSLError:
                'Failed to match server SSL configuration. Ensure the server_context is configured correctly.'
        }
        # #12 Pass through the exception message if available
        return switcher.get(type(e), str(e) if str(e) else 'Please verify server_context is configured correctly.') 
Example #16
Source File: messageboard.py    From labkey-api-python with Apache License 2.0 5 votes vote down vote up
def post_message(server_context, message_title, message_body, render_as, container_path=None):
    """
    Post a message to a message board on a LabKey instance.
    :param server_context: A LabKey server context. See utils.create_server_context.
    :param message_title: The title of the message.
    :param message_body: The content of the message.
    :param render_as: The content of the message.
    :param container_path: Optional container path that can be used to override the server_context container path
    :return: Returns 1 if successful, 0 is post failed.
    """
    message_url = server_context.build_url('announcements', 'insert.api', container_path=container_path)

    message_data = {
        'title': message_title,
        'body': message_body,
        'rendererType': render_as
    }

    try:
        server_context.make_request(message_url, message_data)
    except SSLError as e:
        print("There was problem while attempting to submit the message to " + str(e.geturl()) + ". The HTTP response code was " + str(e.getcode()))
        print("The HTTP client error was: " + format(e))
        return 0
        
    return 1 
Example #17
Source File: unit_test.py    From awscurl with MIT License 5 votes vote down vote up
def my_mock_send_request_verify():
    class Object():
        pass

    def ss(uri, data, headers, method, verify, **kargs):
        print("in mock")
        if not verify:
            raise SSLError
        response = Object()
        response.status_code = 200
        response.text = 'some text'

        return response

    return ss 
Example #18
Source File: utils.py    From twitch-chat-logger with MIT License 5 votes vote down vote up
def get_top_streams(n):
    twitch_api_url = 'https://api.twitch.tv/kraken/streams/?limit=%i' % n
    headers = {'Client-Id': API['CLIENTID']}
    try:
        return json.loads(requests.get(twitch_api_url, headers=headers).text)['streams']
    except (ValueError, ConnectionError, SSLError):
        time.sleep(5)
        return get_top_streams(n) 
Example #19
Source File: http.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def retry_method(self, method, *args, **kwargs):
        if self.proxies:
            # fixme: may be a little loud
            logger.debug("Using proxy %s for: %s", self.proxies["http"], args[0])

        return retry_call(getattr(super(RetryingSession, self), method), fargs=args, fkwargs=kwargs, tries=3, delay=5,
                          exceptions=(exceptions.ConnectionError,
                                      exceptions.ProxyError,
                                      exceptions.SSLError,
                                      exceptions.Timeout,
                                      exceptions.ConnectTimeout,
                                      exceptions.ReadTimeout,
                                      socket.timeout)) 
Example #20
Source File: test_oauth2.py    From ckanext-oauth2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_token_invalid_cert(self):
        helper = self._helper()
        token = OAUTH2TOKEN
        httpretty.register_uri(httpretty.POST, helper.token_endpoint, body=json.dumps(token))

        state = b64encode(json.dumps({'came_from': 'initial-page'}))
        oauth2.toolkit.request = make_request(True, 'data.com', 'callback', {'state': state, 'code': 'code'})

        with self.assertRaises(InsecureTransportError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().fetch_token.side_effect = SSLError('(Caused by SSLError(SSLError("bad handshake: Error([(\'SSL routines\', \'tls_process_server_certificate\', \'certificate verify failed\')],)",),)')
                helper.get_token() 
Example #21
Source File: test_oauth2.py    From ckanext-oauth2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_token_unexpected_ssl_error(self):
        helper = self._helper()
        token = OAUTH2TOKEN
        httpretty.register_uri(httpretty.POST, helper.token_endpoint, body=json.dumps(token))

        state = b64encode(json.dumps({'came_from': 'initial-page'}))
        oauth2.toolkit.request = make_request(True, 'data.com', 'callback', {'state': state, 'code': 'code'})

        with self.assertRaises(SSLError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().fetch_token.side_effect = SSLError('unexpected error')
                helper.get_token() 
Example #22
Source File: test_oauth2.py    From ckanext-oauth2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_identify_invalid_cert(self):

        helper = self._helper()
        token = {'access_token': 'OAUTH_TOKEN'}

        with self.assertRaises(InsecureTransportError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().get.side_effect = SSLError('(Caused by SSLError(SSLError("bad handshake: Error([(\'SSL routines\', \'tls_process_server_certificate\', \'certificate verify failed\')],)",),)')
                helper.identify(token) 
Example #23
Source File: test_oauth2.py    From ckanext-oauth2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_identify_invalid_cert_legacy(self):

        helper = self._helper(conf={"ckan.oauth2.legacy_idm": "True"})
        token = {'access_token': 'OAUTH_TOKEN'}

        with self.assertRaises(InsecureTransportError):
            with patch('ckanext.oauth2.oauth2.requests.get') as requests_get_mock:
                requests_get_mock.side_effect = SSLError('(Caused by SSLError(SSLError("bad handshake: Error([(\'SSL routines\', \'tls_process_server_certificate\', \'certificate verify failed\')],)",),)')
                helper.identify(token) 
Example #24
Source File: test_oauth2.py    From ckanext-oauth2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_identify_unexpected_ssl_error(self):

        helper = self._helper()
        token = {'access_token': 'OAUTH_TOKEN'}

        with self.assertRaises(SSLError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().get.side_effect = SSLError('unexpected error')
                helper.identify(token) 
Example #25
Source File: test_oauth2.py    From ckanext-oauth2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_refresh_token_unexpected_ssl_error(self):
        username = 'user'
        current_token = OAUTH2TOKEN
        helper = self._helper()

        # mock plugin functions
        helper.get_stored_token = MagicMock(return_value=current_token)

        with self.assertRaises(SSLError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().refresh_token.side_effect = SSLError('unexpected error')
                helper.refresh_token(username) 
Example #26
Source File: util.py    From cost-optimization-ec2-right-sizing with Apache License 2.0 5 votes vote down vote up
def retry_on_failure(max_tries=5, http_error_extractor=_extract_http_error):
    def _decorate(f):
        def _retry(*args, **kwargs):
            durations = exponential_backoff(max_tries)
            for i in durations:
                if i > 0:
                    log.debug(u"Sleeping for %f seconds before retrying", i)
                    time.sleep(i)

                try:
                    return f(*args, **kwargs)
                except SSLError as e:
                    log.exception(u"SSLError")
                    raise RemoteError(None, str(e), retry_mode='TERMINAL')
                except ConnectionError as e:
                    log.exception(u"ConnectionError")
                    last_error = RemoteError(None, str(e))
                except HTTPError as e:
                    last_error = http_error_extractor(e.response)
                    if last_error.retry_mode == 'TERMINAL':
                        raise last_error
                    elif last_error.retry_mode == 'RETRIABLE_FOREVER':
                        extend_backoff(durations)

                    log.exception(last_error.strerror)
                except Timeout as e:
                    log.exception(u"Timeout")
                    last_error = RemoteError(None, str(e))
            else:
                raise last_error
        return _retry
    return _decorate 
Example #27
Source File: _repos.py    From dephell with MIT License 5 votes vote down vote up
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 
Example #28
Source File: QAbinance.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def QA_fetch_binance_symbols():
    url = urljoin(Binance_base_url, "/api/v1/exchangeInfo")
    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 /api/v1/exchangeInfo #{}".format(retries - 1))
            time.sleep(0.5)

        if (retries == 0):
            # 成功获取才处理数据,否则继续尝试连接
            symbol_lists = json.loads(req.content)
            if len(symbol_lists["symbols"]) == 0:
                return []
            for symbol in symbol_lists["symbols"]:
                # 只导入上架交易对
                if (symbol['status'] == 'TRADING'):
                    datas.append(symbol)

    return datas 
Example #29
Source File: tokens.py    From tcex with Apache License 2.0 5 votes vote down vote up
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 
Example #30
Source File: util.py    From atomic-reactor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)