requests.exceptions.SSLError

Here are the examples of the python api requests.exceptions.SSLError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

75 Examples 7

Example 1

Project: vdirsyncer
Source File: test_main.py
View license
def test_request_ssl(httpsserver):
    httpsserver.serve_content('')  # we need to serve something

    with pytest.raises(requests.exceptions.SSLError) as excinfo:
        utils.http.request('GET', httpsserver.url)
    assert 'certificate verify failed' in str(excinfo.value)

    utils.http.request('GET', httpsserver.url, verify=False)

Example 2

Project: vdirsyncer
Source File: test_main.py
View license
@pytest.mark.skipif(_fingerprints_broken(),
                    reason='https://github.com/shazow/urllib3/issues/529')
@pytest.mark.parametrize('fingerprint', [
    '94:FD:7A:CB:50:75:A4:69:82:0A:F8:23:DF:07:FC:69:3E:CD:90:CA',
    '19:90:F7:23:94:F2:EF:AB:2B:64:2D:57:3D:25:95:2D'
])
def test_request_ssl_fingerprints(httpsserver, fingerprint):
    httpsserver.serve_content('')  # we need to serve something

    utils.http.request('GET', httpsserver.url, verify=False,
                       verify_fingerprint=fingerprint)
    with pytest.raises(requests.exceptions.SSLError) as excinfo:
        utils.http.request('GET', httpsserver.url,
                           verify_fingerprint=fingerprint)

    with pytest.raises(requests.exceptions.SSLError) as excinfo:
        utils.http.request('GET', httpsserver.url, verify=False,
                           verify_fingerprint=''.join(reversed(fingerprint)))
    assert 'Fingerprints did not match' in str(excinfo.value)

Example 3

Project: python-scaleway
Source File: __init__.py
View license
    def send(self, *args, **kwargs):  # pragma: no cover
        try:
            return super(_CustomHTTPAdapter, self).send(*args, **kwargs)
        except requests.exceptions.SSLError as exc:
            print("SSL error is raised by python-requests. This is probably "
                  "because the required modules to handle SNI aren't "
                  "installed correctly. You should probably uninstall them "
                  "(pip uninstall pyopenssl pyasn1 ndg-httpsclient), install "
                  "the system dependencies required for their installation "
                  "(on Ubuntu, apt-get install python-dev libffi-dev "
                  "libssl-dev) and resintall them (pip install pyopenssl "
                  "pyasn1 ndg-httpsclient).", file=sys.stderr)
            raise

Example 4

Project: sd-agent
Source File: test_nginx.py
View license
    def test_nginx_ssl_validation_enabled(self):
        # Note: Throws an SSLError, because we're attempting to connect to an https endpoint with a self-signed
        #       certificate. In addition, this throws an InsecurePlatformWarning. Both of these are expected;
        #       versions of Python < 2.7.9 have restrictions in their ssl module limiting the configuration
        #       urllib3 can apply. (https://urllib3.readthedocs.org/en/latest/security.html#insecurerequestwarning)
        nginx = load_check('nginx', self.config, self.agent_config)

        # Testing that connection will FAIL with instance 4
        self.assertRaises(requests.exceptions.SSLError, nginx.check, self.config['instances'][4])

Example 5

Project: rows
Source File: cli.py
View license
def _import_table(source, encoding, verify_ssl=True, *args, **kwargs):
    try:
        table = import_from_uri(source,
                                default_encoding=DEFAULT_INPUT_ENCODING,
                                verify_ssl=verify_ssl,
                                encoding=encoding, *args, **kwargs)
    except requests.exceptions.SSLError:
        click.echo('ERROR: SSL verification failed! '
                   'Use `--verify-ssl=no` if you want to ignore.', err=True)
        sys.exit(2)
    else:
        return table

Example 6

Project: SmartQQBot
Source File: http_client.py
View license
    def get(self, url, refer=None):
        try:
            resp = self.session.get(
                url,
                headers=self._get_headers({'Referer': refer or SMART_QQ_REFER}),
                verify=SSL_VERIFY,
            )
        except (excps.ConnectTimeout, excps.HTTPError):
            error_msg = "Failed to send finish request to `{0}`".format(
                url
            )
            logger.exception(error_msg)
            return error_msg
        except requests.exceptions.SSLError:
            logger.exception("SSL连接验证失败,请检查您所在的网络环境。如果需要禁用SSL验证,请修改config.py中的SSL_VERIFY为False")
        else:
            self._cookies.save(COOKIE_FILE, ignore_discard=True, ignore_expires=True)
            return resp.text

Example 7

Project: SmartQQBot
Source File: http_client.py
View license
    def post(self, url, data, refer=None):
        try:
            resp = self.session.post(
                url,
                data,
                headers=self._get_headers({'Referer': refer or SMART_QQ_REFER}),
                verify=SSL_VERIFY,
            )
        except requests.exceptions.SSLError:
            logger.exception("SSL连接验证失败,请检查您所在的网络环境。如果需要禁用SSL验证,请修改config.py中的SSL_VERIFY为False")
        except (excps.ConnectTimeout, excps.HTTPError):
            error_msg = "Failed to send request to `{0}`".format(
                url
            )
            logger.exception(error_msg)
            return error_msg
        else:
            self._cookies.save(COOKIE_FILE, ignore_discard=True, ignore_expires=True)
            return resp.text

Example 8

Project: SmartQQBot
Source File: http_client.py
View license
    def download(self, url, fname):
        with open(fname, "wb") as o_file:
            try:
                resp = self.session.get(url, stream=True, verify=SSL_VERIFY)
            except requests.exceptions.SSLError:
                logger.exception("SSL连接验证失败,请检查您所在的网络环境。如果需要禁用SSL验证,请修改config.py中的SSL_VERIFY为False")
            except (excps.ConnectTimeout, excps.HTTPError):
                error_msg = "Failed to send request to `{0}`".format(
                    url
                )
                logger.exception(error_msg)
                return error_msg
            else:
                o_file.write(resp.raw.read())

Example 9

Project: itunes-iap
Source File: itunesiap_test.py
View license
def test_ssl_request_fail():
    """Test failure making request to itunes server """
    # We're going to return an invalid http status code
    with patch.object(requests, 'post') as mock_post:
        mock_post.side_effect = requests.exceptions.SSLError('Bad ssl')
        request = itunesiap.Request('DummyReceipt')
        try:
            request.verify(verify_request=True)
            assert False
        except itunesiap.exc.RequestError as e:
            assert type(e['exc']) == requests.exceptions.SSLError

Example 10

Project: dd-agent
Source File: test_nginx.py
View license
    def test_nginx_ssl_validation_enabled(self):
        # Note: Throws an SSLError, because we're attempting to connect to an https endpoint with a self-signed
        #       certificate. In addition, this throws an InsecurePlatformWarning. Both of these are expected;
        #       versions of Python < 2.7.9 have restrictions in their ssl module limiting the configuration
        #       urllib3 can apply. (https://urllib3.readthedocs.org/en/latest/security.html#insecurerequestwarning)
        nginx = load_check('nginx', self.config, self.agent_config)

        # Testing that connection will FAIL with instance 4
        self.assertRaises(requests.exceptions.SSLError, nginx.check, self.config['instances'][4])

Example 11

Project: catsnap
Source File: test_image_truck.py
View license
    @raises(TryHTTPError)
    @patch('catsnap.image_truck.requests')
    def test_new_from_url_raises_usefully_for_sni_trouble(self, mock_requests):
        error = requests.exceptions.SSLError(
            urllib3.exceptions.SSLError(
                ssl.SSLError(1, '_ssl.c:503: error:14077410:SSL routines:'
                                'SSL23_GET_SERVER_HELLO:sslv3 alert handshake '
                                'failure')))

        mock_requests.get.side_effect = error

        ImageTruck.new_from_url('https://some.server.using.sni/image.jpg')

Example 12

Project: catsnap
Source File: test_image_truck.py
View license
    @raises(requests.exceptions.SSLError)
    @patch('catsnap.image_truck.requests')
    def test_new_from_url_reraises_non_sni_ssl_errors(self, mock_requests):
        error = requests.exceptions.SSLError(
            urllib3.exceptions.SSLError(
                CertificateError("hostname 'catsinthecity.com' doesn't "
                                 "match 'nossl.edgecastcdn.net'")))

        mock_requests.get.side_effect = error

        ImageTruck.new_from_url('https://catsinthecity.com/image.jpg')

Example 13

Project: HTTPretty
Source File: test_mock.py
View license
@httprettified
def test_httpretty_fails_when_pyopenssl_is_not_replaced():
    ('HTTPretty should fail if PyOpenSSL is installed and we do not remove the monkey patch')

    # When we don't replace the PyOpenSSL monkeypatch
    inject_into_urllib3()

    # And we use HTTPretty on as ssl site
    HTTPretty.register_uri(HTTPretty.GET, "https://yipit.com/",
                           body="Find the best daily deals")

    # Then we get an SSL error
    requests.get.when.called_with('https://yipit.com').should.throw(requests.exceptions.SSLError)

    # Undo injection after test
    extract_from_urllib3()

Example 14

Project: django-mama-cas
Source File: test_models.py
View license
    def test_validate_callback_ssl_error(self):
        """
        If the validation request encounters an SSL error, an
        InvalidProxyCallback should be raised.
        """
        with patch('requests.get') as mock:
            mock.side_effect = requests.exceptions.SSLError
            with self.assertRaises(InvalidProxyCallback):
                ProxyGrantingTicket.objects.validate_callback('http://www.example.com/', 'https://www.example.org/',
                                                              self.pgtid, self.pgtiou)

Example 15

Project: django-mama-cas
Source File: test_models.py
View license
    def test_validate_callback_ssl_error(self):
        """
        If the validation request encounters an SSL error, an
        InvalidProxyCallback should be raised.
        """
        with patch('requests.get') as mock:
            mock.side_effect = requests.exceptions.SSLError
            with self.assertRaises(InvalidProxyCallback):
                ProxyGrantingTicket.objects.validate_callback('http://www.example.com/', 'https://www.example.org/',
                                                              self.pgtid, self.pgtiou)

Example 16

Project: python-yubico-client
Source File: test_yubico.py
View license
    def test_invalid_custom_ca_certs_path(self):
        if hasattr(sys, 'pypy_version_info') or PY3:
            # TODO: Figure out why this breaks PyPy and 3.3
            return

        client = yubico.Yubico('1234', 'secret123456',
                               api_urls=LOCAL_SERVER_HTTPS,
                               ca_certs_bundle_path=os.path.abspath(__file__))

        try:
            client.verify('bad')
        except requests.exceptions.SSLError:
            pass
        else:
            self.fail('SSL exception was not thrown')

Example 17

Project: python-yubico-client
Source File: test_yubico.py
View license
    def test_invalid_custom_ca_certs_path(self):
        if hasattr(sys, 'pypy_version_info') or PY3:
            # TODO: Figure out why this breaks PyPy and 3.3
            return

        client = yubico.Yubico('1234', 'secret123456',
                               api_urls=LOCAL_SERVER_HTTPS,
                               ca_certs_bundle_path=os.path.abspath(__file__))

        try:
            client.verify('bad')
        except requests.exceptions.SSLError:
            pass
        else:
            self.fail('SSL exception was not thrown')

Example 18

View license
    @deferred()
    def test_check_https_fails(self):
        self.pb._domain = "localhost:%s" % (self.https_port,)

        def check(*args):
            with self.assertRaises(requests.exceptions.SSLError):
                self.pb._check_https()
        return threads.deferToThread(check)

Example 19

View license
    @deferred()
    def test_check_https_fails(self):
        self.pb._domain = "localhost:%s" % (self.https_port,)

        def check(*args):
            with self.assertRaises(requests.exceptions.SSLError):
                self.pb._check_https()
        return threads.deferToThread(check)

Example 20

View license
    @deferred()
    def test_check_api_certificate_fails(self):
        self.pb._provider_config = ProviderConfig()
        self.pb._provider_config.get_api_uri = mock.MagicMock(
            return_value="https://localhost:%s" % (self.https_port,))
        self.pb._provider_config.get_ca_cert_path = mock.MagicMock(
            return_value=os.path.join(
                os.path.split(__file__)[0],
                "wrongcert.pem"))
        self.pb._provider_config.get_api_version = mock.MagicMock(
            return_value="1")

        self.pb._should_proceed_cert = mock.MagicMock(return_value=True)

        def check(*args):
            with self.assertRaises(requests.exceptions.SSLError):
                self.pb._check_api_certificate()
        d = threads.deferToThread(check)
        return d

Example 21

View license
    @deferred()
    def test_check_api_certificate_fails(self):
        self.pb._provider_config = ProviderConfig()
        self.pb._provider_config.get_api_uri = mock.MagicMock(
            return_value="https://localhost:%s" % (self.https_port,))
        self.pb._provider_config.get_ca_cert_path = mock.MagicMock(
            return_value=os.path.join(
                os.path.split(__file__)[0],
                "wrongcert.pem"))
        self.pb._provider_config.get_api_version = mock.MagicMock(
            return_value="1")

        self.pb._should_proceed_cert = mock.MagicMock(return_value=True)

        def check(*args):
            with self.assertRaises(requests.exceptions.SSLError):
                self.pb._check_api_certificate()
        d = threads.deferToThread(check)
        return d

Example 22

Project: tower-cli
Source File: test_api.py
View license
    def test_failed_suggestion_protocol(self):
        """Establish that if connection fails and protocol not given,
        tower-cli suggests that to the user."""
        with settings.runtime_values(verbose=False, host='foo.co'):
            with mock.patch.object(Session, 'request') as req:
                req.side_effect = requests.exceptions.SSLError
                with mock.patch.object(click, 'secho') as secho:
                    with self.assertRaises(exc.ConnectionError):
                        client.get('/ping/')
                    self.assertTrue(secho.called)

Example 23

Project: tower-cli
Source File: test_api.py
View license
    def test_failed_suggestion_protocol(self):
        """Establish that if connection fails and protocol not given,
        tower-cli suggests that to the user."""
        with settings.runtime_values(verbose=False, host='foo.co'):
            with mock.patch.object(Session, 'request') as req:
                req.side_effect = requests.exceptions.SSLError
                with mock.patch.object(click, 'secho') as secho:
                    with self.assertRaises(exc.ConnectionError):
                        client.get('/ping/')
                    self.assertTrue(secho.called)

Example 24

View license
    def test_requests_exception(self):
        """Exception during API call should be AnymailAPIError"""
        # (The post itself raises an error -- different from returning a failure response)
        from requests.exceptions import SSLError  # a low-level requests exception
        self.mock_request.side_effect = SSLError("Something bad")
        with self.assertRaisesMessage(AnymailRequestsAPIError, "Something bad") as cm:
            self.message.send()
        self.assertIsInstance(cm.exception, SSLError)  # also retains specific requests exception class

        # Make sure fail_silently is respected
        self.mock_request.side_effect = SSLError("Something bad")
        sent = mail.send_mail('Subject', 'Body', '[email protected]', ['[email protected]'], fail_silently=True)
        self.assertEqual(sent, 0)

Example 25

View license
    def test_requests_exception(self):
        """Exception during API call should be AnymailAPIError"""
        # (The post itself raises an error -- different from returning a failure response)
        from requests.exceptions import SSLError  # a low-level requests exception
        self.mock_request.side_effect = SSLError("Something bad")
        with self.assertRaisesMessage(AnymailRequestsAPIError, "Something bad") as cm:
            self.message.send()
        self.assertIsInstance(cm.exception, SSLError)  # also retains specific requests exception class

        # Make sure fail_silently is respected
        self.mock_request.side_effect = SSLError("Something bad")
        sent = mail.send_mail('Subject', 'Body', '[email protected]', ['[email protected]'], fail_silently=True)
        self.assertEqual(sent, 0)

Example 26

Project: keystoneauth
Source File: test_session.py
View license
    def test_ssl_error_message(self):
        error = uuid.uuid4().hex

        self.stub_url('GET', exc=requests.exceptions.SSLError(error))
        session = client_session.Session()

        # The exception should contain the URL and details about the SSL error
        msg = 'SSL exception connecting to %(url)s: %(error)s' % {
            'url': self.TEST_URL, 'error': error}
        self.assertRaisesRegex(exceptions.SSLError,
                               msg,
                               session.get,
                               self.TEST_URL)

Example 27

View license
    def test_ssl_error_message(self):
        error = uuid.uuid4().hex

        def _ssl_error(request, context):
            raise requests.exceptions.SSLError(error)

        self.stub_url('GET', text=_ssl_error)
        session = client_session.Session()

        # The exception should contain the URL and details about the SSL error
        msg = _('SSL exception connecting to %(url)s: %(error)s') % {
            'url': self.TEST_URL, 'error': error}
        six.assertRaisesRegex(self,
                              exceptions.SSLError,
                              msg,
                              session.get,
                              self.TEST_URL)

Example 28

Project: python-tackerclient
Source File: test_ssl.py
View license
    def test_proper_exception_is_raised_when_cert_validation_fails(self):
        http = HTTPClient(token=AUTH_TOKEN, endpoint_url=END_URL)

        self.mox.StubOutWithMock(HTTPClient, 'request')
        HTTPClient.request(
            URL, METHOD, headers=mox.IgnoreArg()
        ).AndRaise(requests.exceptions.SSLError)
        self.mox.ReplayAll()

        self.assertRaises(
            exceptions.SslCertificateValidationError,
            http._cs_request,
            URL, METHOD
        )
        self.mox.VerifyAll()

Example 29

Project: smolder
Source File: charcoal.py
View license
    def run(self):
        with warnings.catch_warnings():
            try:
                LOG.debug("Verify is a: {0}, with value: {1}".format(type(self.verify), self.verify))
                if self.verify:
                    warnings.simplefilter("error", requests.exceptions.SSLError)
                start = int(round(time.time() * 1000))
                if self.test["protocol"] != 'tcp':
                    self.req = requests.request(self.test['method'].upper(), verify=self.verify, **self.inputs)
                else:
                    tcptest.tcp_test(self.host, self.port)
                end = int(round(time.time() * 1000))
                self.duration_ms = end - start
            except (RuntimeWarning, requests.exceptions.SSLError):
                warnings.simplefilter("default", requests.exceptions.SSLError)
                start = int(round(time.time() * 1000))
                try:
                    self.req = requests.request(self.test['method'].upper(), verify=self.verify, **self.inputs)
                except (requests.exceptions.SSLError) as e:
                    message, status = self.fail_test("Certificate verify failed and not ignored by inputs['verify']: %s" % (str(e)))
                    self.add_output("SSLVerify", message, status)
                    return
                end = int(round(time.time() * 1000))
                self.duration_ms = end - start
                if not self.verify_specified:
                    message, status = self.fail_test("Insecure request not ignored by inputs['verify']")
                    self.add_output("SecureRequest", message, status)
                else:
                    if self.verify:
                        message, status = self.fail_test("Insecure request made")
                        self.add_output("SecureRequest", message, status)
                    else:
                        message, status = self.warn_test("Insecure request made and ignored")
                        self.add_output("SecureRequest", message, status)
        if self.test["protocol"] != 'tcp':
            self.output.append(dict(self.req.headers), sec='response_headers')
            self.output.append(self.req.status_code, sec='response_status_code')
            if 'show_body' in self.test:
                try:
                    req_content = self.req.content.decode()
                except UnicodeDecodeError:
                    req_content = self.req.content
                self.output.append(req_content)

            for plugin_info in manager.getAllPlugins():
                for outcome in self.test['outcomes']:
                    if plugin_info.name == outcome:
                        manager.activatePluginByName(plugin_info.name)
                        message, status = plugin_info.plugin_object.run(self)
                        self.add_output(plugin_info.name, message, status)
                        manager.deactivatePluginByName(plugin_info.name)

Example 30

Project: pulp
Source File: adapters.py
View license
    def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
        """Sends PreparedRequest object. Returns Response object.

        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
        :param stream: (optional) Whether to stream the request content.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a (`connect timeout, read
            timeout <user/advanced.html#timeouts>`_) tuple.
        :type timeout: float or tuple
        :param verify: (optional) Whether to verify SSL certificates.
        :param cert: (optional) Any user-provided SSL certificate to be trusted.
        :param proxies: (optional) The proxies dictionary to apply to the request.
        """
        conn = self.get_connection(request.url, proxies, verify, cert)

        url = self.request_url(request, proxies)
        self.add_headers(request)

        chunked = not (request.body is None or 'Content-Length' in request.headers)

        if isinstance(timeout, tuple):
            try:
                connect, read = timeout
                timeout = TimeoutSauce(connect=connect, read=read)
            except ValueError as e:
                # this may raise a string formatting error.
                err = ("Invalid timeout {0}. Pass a (connect, read) "
                       "timeout tuple, or a single float to set "
                       "both timeouts to the same value".format(timeout))
                raise ValueError(err)
        else:
            timeout = TimeoutSauce(connect=timeout, read=timeout)

        try:
            if not chunked:
                resp = conn.urlopen(
                    method=request.method,
                    url=url,
                    body=request.body,
                    headers=request.headers,
                    redirect=False,
                    assert_same_host=False,
                    preload_content=False,
                    decode_content=False,
                    retries=self.max_retries,
                    timeout=timeout
                )

            # Send the request.
            else:
                if hasattr(conn, 'proxy_pool'):
                    conn = conn.proxy_pool

                low_conn = conn._get_conn(timeout=timeout)

                try:
                    low_conn.putrequest(request.method,
                                        url,
                                        skip_accept_encoding=True)

                    for header, value in request.headers.items():
                        low_conn.putheader(header, value)

                    low_conn.endheaders()

                    for i in request.body:
                        low_conn.send(hex(len(i))[2:].encode('utf-8'))
                        low_conn.send(b'\r\n')
                        low_conn.send(i)
                        low_conn.send(b'\r\n')
                    low_conn.send(b'0\r\n\r\n')

                    r = low_conn.getresponse()
                    resp = HTTPResponse.from_httplib(
                        r,
                        pool=conn,
                        connection=low_conn,
                        preload_content=False,
                        decode_content=False
                    )
                except:
                    # If we hit any problems here, clean up the connection.
                    # Then, reraise so that we can handle the actual exception.
                    low_conn.close()
                    raise
                else:
                    # All is well, return the connection to the pool.
                    conn._put_conn(low_conn)

        except (ProtocolError, socket.error) as err:
            raise ConnectionError(err, request=request)

        except MaxRetryError as e:
            if isinstance(e.reason, ConnectTimeoutError):
                raise ConnectTimeout(e, request=request)

            if isinstance(e.reason, ResponseError):
                raise RetryError(e, request=request)

            raise ConnectionError(e, request=request)

        except _ProxyError as e:
            raise ProxyError(e)

        except (_SSLError, _HTTPError) as e:
            if isinstance(e, _SSLError):
                raise SSLError(e, request=request)
            elif isinstance(e, ReadTimeoutError):
                raise ReadTimeout(e, request=request)
            else:
                raise

        return self.build_response(request, resp)

Example 31

Project: pydrill
Source File: requests_conn.py
View license
    def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=()):
        url = self.base_url + url
        if params:
            url = '%s?%s' % (url, urlencode(params or {}))

        if timeout is None:
            timeout = self.timeout

        start = time.time()
        try:
            response = self.session.request(method, url, data=body, headers={'Content-Type': 'application/json'},
                                            timeout=timeout)
            duration = time.time() - start
            raw_data = response.text
        except requests.exceptions.SSLError as e:
            self.log_request_fail(method, url, body, time.time() - start, exception=e)
            raise SSLError('N/A', str(e), e)
        except requests.Timeout as e:
            self.log_request_fail(method, url, body, time.time() - start, exception=e)
            raise ConnectionTimeout('TIMEOUT', str(e), e)
        except requests.ConnectionError as e:
            self.log_request_fail(method, url, body, time.time() - start, exception=e)
            raise ConnectionError('N/A', str(e), e)

        # raise errors based on http status codes, let the client handle those if needed
        if not (200 <= response.status_code < 300) and response.status_code not in ignore:
            self.log_request_fail(method, url, body, duration, response.status_code)
            self._raise_error(response.status_code, raw_data)

        self.log_request_success(method, url, response.request.path_url, body, response.status_code, raw_data, duration)

        return response, raw_data, duration

Example 32

Project: headphones
Source File: request.py
View license
def request_response(url, method="get", auto_raise=True,
                     whitelist_status_code=None, lock=fake_lock, **kwargs):
    """
    Convenient wrapper for `requests.get', which will capture the exceptions
    and log them. On success, the Response object is returned. In case of a
    exception, None is returned.

    Additionally, there is support for rate limiting. To use this feature,
    supply a tuple of (lock, request_limit). The lock is used to make sure no
    other request with the same lock is executed. The request limit is the
    minimal time between two requests (and so 1/request_limit is the number of
    requests per seconds).
    """

    # Convert whitelist_status_code to a list if needed
    if whitelist_status_code and type(whitelist_status_code) != list:
        whitelist_status_code = [whitelist_status_code]

    # Disable verification of SSL certificates if requested. Note: this could
    # pose a security issue!
    kwargs["verify"] = bool(headphones.CONFIG.VERIFY_SSL_CERT)

    # This fix is put in place for systems with broken SSL (like QNAP)
    if not headphones.CONFIG.VERIFY_SSL_CERT and sys.version_info >= (2, 7, 9):
        try:
            import ssl
            ssl._create_default_https_context = ssl._create_unverified_context
        except:
            pass

    # Map method to the request.XXX method. This is a simple hack, but it
    # allows requests to apply more magic per method. See lib/requests/api.py.
    request_method = getattr(requests, method.lower())

    try:
        # Request URL and wait for response
        with lock:
            logger.debug(
                "Requesting URL via %s method: %s", method.upper(), url)
            response = request_method(url, **kwargs)

        # If status code != OK, then raise exception, except if the status code
        # is white listed.
        if whitelist_status_code and auto_raise:
            if response.status_code not in whitelist_status_code:
                try:
                    response.raise_for_status()
                except:
                    logger.debug(
                        "Response status code %d is not white "
                        "listed, raised exception", response.status_code)
                    raise
        elif auto_raise:
            response.raise_for_status()

        return response
    except requests.exceptions.SSLError as e:
        if kwargs["verify"]:
            logger.error(
                "Unable to connect to remote host because of a SSL error. "
                "It is likely that your system cannot verify the validity"
                "of the certificate. The remote certificate is either "
                "self-signed, or the remote server uses SNI. See the wiki for "
                "more information on this topic.")
        else:
            logger.error(
                "SSL error raised during connection, with certificate "
                "verification turned off: %s", e)
    except requests.ConnectionError:
        logger.error(
            "Unable to connect to remote host. Check if the remote "
            "host is up and running.")
    except requests.Timeout:
        logger.error(
            "Request timed out. The remote host did not respond in a timely "
            "manner.")
    except requests.HTTPError as e:
        if e.response is not None:
            if e.response.status_code >= 500:
                cause = "remote server error"
            elif e.response.status_code >= 400:
                cause = "local client error"
            else:
                # I don't think we will end up here, but for completeness
                cause = "unknown"

            logger.error(
                "Request raise HTTP error with status code %d (%s).",
                e.response.status_code, cause)

            # Debug response
            if headphones.VERBOSE:
                server_message(e.response)
        else:
            logger.error("Request raised HTTP error.")
    except requests.RequestException as e:
        logger.error("Request raised exception: %s", e)

Example 33

Project: pyswagger
Source File: swagger.py
View license
    def __getattr__(self, fn):
        def callback(self, *args, **kwargs):
            """Callback method for issuing requests via the operations
            defined in the paths"""
            try:
                # If the `path` argument is not passed, raise a
                # `ValueError` exception.
                path = args[0]
            except IndexError:
                raise ValueError('Path argument not provided')
            if path not in self.paths:
                # If the `path` does not exist, raise `InvalidPathError`
                # exception.
                raise InvalidPathError(path)
            operation = self.paths[path][fn]
            if 'security' in operation:
                if 'auth' in kwargs:
                    auth = kwargs.pop('auth')
                    self.auth = auth
            # Use string interpolation to replace placeholders with
            # keyword arguments.
            path = path.format(**kwargs)
            url = '{baseUri}{path}'.format(baseUri=self._baseUri, path=path)
            # If the `body` keyword argument exists, remove it from the
            # keyword argument dictionary and pass it as an argument
            # when issuing the request.
            body = kwargs.pop('body', {})
            # Override the default headers defined in the root schema.
            produces = kwargs.pop('produces', self.DefaultFormat)
            if produces not in operation['produces']:
                # The MIME type does not exist in the
                # content-negotiation header.
                return
            headers = {
                'Accept': produces,
            }
            try:
                response = self._session.request(
                    fn, url, params=kwargs, data=body, timeout=self._timeout,
                    headers=headers
                )
            except requests.exceptions.SSLError:
                # If the request fails via a `SSLError`, re-instantiate
                # the request with the `verify` argument assigned  to
                # `False`.
                response = self._session.request(
                    fn, url, params=kwargs, data=body, verify=False,
                    timeout=self._timeout, headers=headers
                )
            if response.status_code not in list(range(200, 300)):
                # If the response status code is a non-2XX code, raise a
                # `ResponseError`. The `reason` variable attempts to
                # retrieve the `description` key if it is provided in
                # the `response` object. Otherwise, the default response
                # `reason` is used.
                try:
                    reason = (
                        operation['responses'][str(response.status_code)].get(
                            'description', response.reason
                        )
                    )
                except KeyError:
                    # Use the default `status_code` and `reason`
                    # returned from the response.
                    reason = response.reason
                raise self.ResponseError(response.status_code, reason)
            return response
        if fn not in self.DefaultOperations:
            # If the method does not exist in the `DefaultOperations`,
            # raise an `InvalidOperationError` exception.
            raise InvalidOperationError(fn)
        return callback.__get__(self)

Example 34

Project: reppy
Source File: test_robots.py
View license
    def test_ssl_exception(self):
        '''Raises a ReppyException on SSL errors.'''
        with mock.patch.object(robots.requests, 'get', side_effect=SSLError('Kaboom')):
            with self.assertRaises(robots.exceptions.SSLException):
                robots.Robots.fetch('https://localhost:8080/robots.txt')

Example 35

Project: SiCKRAGE
Source File: exceptions.py
View license
def handle_exception(func):
    @wraps(func)
    def handle(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except requests.exceptions.SSLError as e:
            if ssl.OPENSSL_VERSION_INFO < (1, 0, 1, 5):
                sickrage.srCore.srLogger.info(
                    "SSL Error requesting url: '{}' You have {}, try upgrading OpenSSL to 1.0.1e+".format(e.request.url,
                                                                                                          ssl.OPENSSL_VERSION))

            if sickrage.srCore.srConfig.SSL_VERIFY:
                sickrage.srCore.srLogger.info(
                    "SSL Error requesting url: '{}' Try disabling Cert Verification under advanced settings").format(e.request.url)

            sickrage.srCore.srLogger.error("SSL Error: {}".format(e.message))
            #sickrage.srCore.srLogger.debug(traceback.format_exc())
        except requests.exceptions.RequestException as e:
            sickrage.srCore.srLogger.error("Request failed: {}".format(e.message))
            #sickrage.srCore.srLogger.debug(traceback.format_exc())

    return handle

Example 36

Project: SiCKRAGE
Source File: session.py
View license
    def request(self, method, url, headers=None, params=None, cache=True, *args, **kwargs):
        url = self.normalize_url(url)
        kwargs.setdefault('params', {}).update(params or {})
        kwargs.setdefault('headers', {}).update(headers or {})

        # if method == 'POST':
        #    self.session.headers.update({"Content-type": "application/x-www-form-urlencoded"})
        kwargs.setdefault('headers', {}).update({'Accept-Encoding': 'gzip, deflate'})
        kwargs.setdefault('headers', {}).update(random.choice(USER_AGENTS))

        # request session ssl verify
        kwargs['verify'] = False
        if sickrage.srCore.srConfig.SSL_VERIFY:
            try:
                kwargs['verify'] = certifi.where()
            except:
                pass

        # request session proxies
        if 'Referer' not in kwargs.get('headers', {}) and sickrage.srCore.srConfig.PROXY_SETTING:
            sickrage.srCore.srLogger.debug("Using global proxy: " + sickrage.srCore.srConfig.PROXY_SETTING)
            scheme, address = urllib2.splittype(sickrage.srCore.srConfig.PROXY_SETTING)
            address = \
                ('http://{}'.format(sickrage.srCore.srConfig.PROXY_SETTING), sickrage.srCore.srConfig.PROXY_SETTING)[
                    scheme]
            kwargs.setdefault('proxies', {}).update({"http": address, "https": address})
            kwargs.setdefault('headers', {}).update({'Referer': address})

        # setup session caching
        if cache:
            cache_file = os.path.abspath(os.path.join(sickrage.DATA_DIR, 'sessions.db'))
            cachecontrol.CacheControl(self,
                                      cache=DBCache(cache_file),
                                      heuristic=ExpiresAfter(days=7))

        # get web response
        response = super(srSession, self).request(method, url, *args, **kwargs).result()

        try:
            # check web response for errors
            response.raise_for_status()
        except requests.exceptions.SSLError as e:
            if ssl.OPENSSL_VERSION_INFO < (1, 0, 1, 5):
                sickrage.srCore.srLogger.info(
                    "SSL Error requesting url: '{}' You have {}, try upgrading OpenSSL to 1.0.1e+".format(
                        e.request.url, ssl.OPENSSL_VERSION))

            if sickrage.srCore.srConfig.SSL_VERIFY:
                sickrage.srCore.srLogger.info(
                    "SSL Error requesting url: '{}' Try disabling Cert Verification on the advanced tab of /config/general".format(
                        e.request.url))
        except Exception as e:
            sickrage.srCore.srLogger.debug(e.message)

        return response

Example 37

Project: python-isilon-api
Source File: test_isilon.py
View license
    def test_bad_ssl_cert(self):
        api = isilon.API(fqdn,user,password)
        self.assertRaises(requests.exceptions.SSLError,api.session.connect)

Example 38

Project: DockCI
Source File: exceptions.py
View license
    def root_exception(self, exception=None):
        """
        Unwrap the tangled mess of requests exceptions to get the root cause
        of the given exception
        """
        if exception is None:
            exception = self.exception

        if exception is None:
            raise ValueError("No exception given")

        if isinstance(exception, requests.exceptions.SSLError):
            if isinstance(exception.args[0], Exception):
                return self.root_exception(exception.args[0])

            return exception.args[1]

        elif isinstance(exception, requests.exceptions.ConnectionError):
            return self.root_exception(exception.args[0])
        elif isinstance(exception, ProtocolError):
            return self.root_exception(exception.args[1])

        return exception

Example 39

Project: DockCI
Source File: config.py
View license
    def validate(self):
        with self.parent_validation(Config):
            errors = []

            import docker
            for docker_host in self.docker_hosts:
                docker_client_args = client_kwargs_from_config(docker_host)

                try:
                    # pylint:disable=unused-variable
                    client = docker.Client(**docker_client_args)
                    client.ping()

                except docker.errors.DockerException as ex:
                    # pylint:disable=unpacking-non-sequence
                    message, *_ = ex.args
                    errors.append(message)

                except requests.exceptions.SSLError as ex:
                    errors.append(str(DockerUnreachableError(
                        docker_client_args['base_url'], ex,
                    )))

            if self.external_url is not None and self.external_url != '':
                external_url = urlparse(self.external_url)
                if external_url.scheme.lower() not in ('http', 'https'):
                    errors.append("External URL must be HTTP, or HTTPS")
                if not external_url.netloc:
                    errors.append("External URL must contain a host name")

                invalid_url_parts = (
                    bool(getattr(external_url, url_part))
                    for url_part
                    in ('params', 'query', 'fragment')
                )
                if any(invalid_url_parts):
                    errors.append("External URL can only include scheme, "
                                  "host, port, and path")

            for url_re in self.oauth_authorized_redirects:
                try:
                    re.compile(url_re)
                except RegexError as ex:
                    errors.append(
                        "Authorized OAuth URL regex error: %s in '%s'" % (
                            ex, url_re,
                        )
                    )

            if errors:
                raise ValidationError(errors)

        return True

Example 40

Project: DockCI
Source File: test_exceptions.py
View license
    @pytest.mark.parametrize('args,expected', [
        (
            (docker.Client('http://localhost:2375'), None, 'testing'),
            "Error with the Docker server 'http://localhost:2375': testing",
        ),
        (
            (
                docker.Client('http://localhost:2375'),
                ValueError('different'),
                'testing',
            ),
            "Error with the Docker server 'http://localhost:2375': testing",
        ),
        (
            (docker.Client('http://localhost:2375'), CONN_REFUSED),
            "Error with the Docker server 'http://localhost:2375': "
            "[Errno 61] Connection refused",
        ),
        (
            (
                docker.Client('http://localhost:2375'),
                ValueError('testing'),
            ),
            "Error with the Docker server 'http://localhost:2375': testing",
        ),
        (
            (
                docker.Client('http://localhost:2375'), ConnectionError(
                    ProtocolError('Connection aborted.', CONN_REFUSED))
            ),
            "Error with the Docker server 'http://localhost:2375': "
            "[Errno 61] Connection refused",
        ),
        (
            (
                docker.Client('http://localhost:2375'),
                SSLError(SSLError(SSLError(
                    1,
                    '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify '
                    'failed (_ssl.c:600)'
                )))
            ),
            "Error with the Docker server 'http://localhost:2375': "
            "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify "
            "failed (_ssl.c:600)",
        ),
        (
            ('http://strserv:2375', None, 'testing'),
            "Error with the Docker server 'http://strserv:2375': testing",
        ),
        (
            ('http://strserv:2375', CONN_REFUSED),
            "Error with the Docker server 'http://strserv:2375': "
            "[Errno 61] Connection refused",
        ),
    ])
    def test_str(self, args, expected):
        """
        Ensure that messages are retrieved from root exceptions, and overridden
        by init message as expected
        """
        test_ex = DockerUnreachableError(*args)
        assert str(test_ex) == expected

Example 41

Project: pywikibot-core
Source File: http.py
View license
def error_handling_callback(request):
    """
    Raise exceptions and log alerts.

    @param request: Request that has completed
    @type request: L{threadedhttp.HttpRequest}
    """
    # TODO: do some error correcting stuff
    if isinstance(request.data, requests.exceptions.SSLError):
        if SSL_CERT_VERIFY_FAILED_MSG in str(request.data):
            raise FatalServerError(str(request.data))

    # if all else fails
    if isinstance(request.data, Exception):
        raise request.data

    if request.status == 504:
        raise Server504Error("Server %s timed out" % request.hostname)

    if request.status == 414:
        raise Server414Error('Too long GET request')

    # HTTP status 207 is also a success status for Webdav FINDPROP,
    # used by the version module.
    if request.status not in (200, 207):
        warning('Http response status {0}'.format(request.data.status_code))

Example 42

Project: uphold-sdk-python
Source File: uphold.py
View license
    def _post(self, uri, params):
        """
        """
        url = 'https://' + self.host + self._build_url(uri)

        try:
            if self.pat:
                self._debug("Using PAT")
                response = self.session.post(url, data=params, headers=self.headers, auth=(self.pat, 'X-OAuth-Basic'))
            elif self.username:
                self._debug("Using Basic Auth")
                self.session.auth = ( self.username, self.password )
                if self.otp:
                    self._debug("Using verification code: " + self.otp)
                    self.headers['X-Bitreserve-OTP'] = self.otp
                self._debug(self.headers)
                response = self.session.post(url, data=params, headers=self.headers)
            else:
                response = self.session.post(url, data=params, headers=self.headers)

            self._update_rate_limit( response.headers )

            if 'X-Bitreserve-OTP' in response.headers:
                self._debug("OTP Required!")
                raise VerificationRequired("OTP Required")
            elif response.status_code == 429:
                self._debug("Rate Limit Error!")
                raise RateLimitError(response.headers)

        except requests.exceptions.SSLError as e:
            # Handle incorrect certificate error.
            self._debug("Failed certificate check: " + str(e))
            exit()

        data = json.loads(response.text)
        if 'X-Bitreserve-OTP' in self.headers:
            del self.headers['X-Bitreserve-OTP']
        return data

Example 43

Project: uphold-sdk-python
Source File: uphold.py
View license
    def _get(self, uri):
        """
        """
        url = 'https://' + self.host + self._build_url(uri)

        # You're ready to make verified HTTPS requests.
        try:
            if self.pat:
                self._debug("Using PAT")
                response = self.session.get(url, headers=self.headers, auth=(self.pat, 'X-OAuth-Basic'))
            elif self.username:
                self._debug("Using Basic Auth")
                self.session.auth = ( self.username, self.password )
                if self.otp:
                    self._debug("Using verification code: " + self.otp)
                    self.headers['X-Bitreserve-OTP'] = self.otp
                self._debug(self.headers)
                response = self.session.get(url, headers=self.headers)
            else:
                response = self.session.get(url, headers=self.headers)

            self._update_rate_limit( response.headers )

            if 'X-Bitreserve-OTP' in response.headers:
                self._debug("OTP Required!")
                raise VerificationRequired("OTP Required")
            elif response.status_code == 429:
                self._debug("Rate Limit Error!")
                raise RateLimitError(response.headers)

        except requests.exceptions.SSLError as e:
            # Handle incorrect certificate error.
            self._debug("Failed certificate check: " + str(e))
            exit()

        data = json.loads(response.text)
        if 'X-Bitreserve-OTP' in self.headers:
            del self.headers['X-Bitreserve-OTP']
        return data

Example 44

Project: kubeshift
Source File: base.py
View license
    def request(self, method, url, data=None, headers=None):
        """
        Complete the request to the API and fails if the status_code is != 200/201.

        :param str method: put/get/post/patch
        :param str url: url of the api call
        :param dict data: object of the data that is being passed (will be converted to json)
        :param dict headers: request header
        """
        status_code = None
        return_data = None

        try:
            res = self.session.request(method, url, headers=headers, json=data)
            status_code = res.status_code
            if res.ok and res.text:
                return_data = res.json()
        except requests.exceptions.SSLError:
            raise KubeConnectionError('SSL/TLS ERROR: invalid certificate')
        except requests.exceptions.ConnectTimeout:
            raise KubeConnectionError('Timeout when connecting to  %s' % url)
        except requests.exceptions.ReadTimeout:
            raise KubeConnectionError('Timeout when reading from %s' % url)
        except requests.exceptions.ConnectionError:
            raise KubeConnectionError('Refused connection to %s' % url)

        # 200 = OK
        # 201 = PENDING
        # EVERYTHING ELSE == FAIL
        if status_code is not 200 and status_code is not 201:
            raise KubeRequestError('Unable to complete request: Status: %s, Error: %s'
                                   % (status_code, res.reason))
        return return_data

Example 45

Project: kubeshift
Source File: test_base.py
View license
    def test_request_ssl_error(self):
        client = KubeBase(self.config)
        with patch.object(client.session, 'request', side_effect=requests.exceptions.SSLError):
            with self.assertRaises(KubeConnectionError):
                client.request('get', 'http://localhost:8080')

Example 46

Project: n6sdk
Source File: client.py
View license
    def get_stream(self, url, params=None):
        message = None
        code = None
        try:
            self._response = self._session.get(url, stream=True, cert=self._cert, verify=self._verify)
            self._response.raise_for_status()
        except requests.exceptions.SSLError as ssl_error:
            message = "SSL Certificate verification failed."
            exception = ssl_error
        except requests.exceptions.HTTPError as http_error:
            message = "HTTP error."
            exception = '{} (`{}`)'.format(
                http_error, self._response.content.replace('\n', ' ').strip())
            code = self._response.status_code
        except requests.exceptions.Timeout as timeout_error:
            message = "Connection timeout."
            exception = timeout_error
        except requests.exceptions.RequestException as req_error:
            message = "Connection failed due to unknown problems."
            exception = req_error
        if message:
            exc = APIClientException("{} {}".format(message, exception))
            exc.code = code
            raise exc
        if self._response and self._response.status_code == requests.codes.ok:
            for line in self._response.iter_lines(4096):
                if line:
                    # NOTE: here we use cjson.decode() instead of
                    # stdlib's json.loads() -- because of the bug
                    # https://bugs.python.org/issue11489 which
                    # affects all pre-2.7.7 releases of CPython
                    yield cjson.decode(line)

Example 47

Project: n6sdk
Source File: client.py
View license
    def get_stream(self, url, params=None):
        message = None
        code = None
        try:
            self._response = self._session.get(url, stream=True, cert=self._cert, verify=self._verify)
            self._response.raise_for_status()
        except requests.exceptions.SSLError as ssl_error:
            message = "SSL Certificate verification failed."
            exception = ssl_error
        except requests.exceptions.HTTPError as http_error:
            message = "HTTP error."
            exception = '{} (`{}`)'.format(
                http_error, self._response.content.replace('\n', ' ').strip())
            code = self._response.status_code
        except requests.exceptions.Timeout as timeout_error:
            message = "Connection timeout."
            exception = timeout_error
        except requests.exceptions.RequestException as req_error:
            message = "Connection failed due to unknown problems."
            exception = req_error
        if message:
            exc = APIClientException("{} {}".format(message, exception))
            exc.code = code
            raise exc
        if self._response and self._response.status_code == requests.codes.ok:
            for line in self._response.iter_lines(4096):
                if line:
                    # NOTE: here we use cjson.decode() instead of
                    # stdlib's json.loads() -- because of the bug
                    # https://bugs.python.org/issue11489 which
                    # affects all pre-2.7.7 releases of CPython
                    yield cjson.decode(line)

Example 48

View license
    def _assert_ssl_error(self, **kwargs):
        client = self._create_rest_client(**kwargs)
        with self.assertRaises(requests.exceptions.SSLError):
            client.manager.get_status()

Example 49

Project: geocoder
Source File: base.py
View license
    def _connect(self, **kwargs):
        self.status_code = 'Unknown'
        self.timeout = kwargs.get('timeout', 5.0)
        self.proxies = kwargs.get('proxies', '')
        try:
            r = self.rate_limited_get(
                self.url,
                params=self.params,
                headers=self.headers,
                timeout=self.timeout,
                proxies=self.proxies
            )
            self.status_code = r.status_code
            self.url = r.url
            if r.content:
                self.status_code = 200
        except (KeyboardInterrupt, SystemExit):
            raise
        except requests.exceptions.SSLError:
            self.status_code = 495
            self.error = 'ERROR - SSLError'

        # Open JSON content from Request connection
        if self.status_code == 200:
            try:
                self.content = r.json()
            except:
                self.status_code = 400
                self.error = 'ERROR - JSON Corrupted'
                self.content = r.content

Example 50

Project: sacad
Source File: http_helpers.py
View license
def query(url, *, session, watcher=None, post_data=None, headers=None, verify=True):
  """ Send a GET/POST request, retry if it fails, and return response content. """
  if headers is None:
    headers = {}
  if "User-Agent" not in headers:
    headers["User-Agent"] = DEFAULT_USER_AGENT

  for attempt, _ in enumerate(redo.retrier(attempts=HTTP_MAX_ATTEMPTS,
                                           sleeptime=1.5,
                                           max_sleeptime=5,
                                           sleepscale=1.25,
                                           jitter=1),
                              1):
    try:
      with contextlib.ExitStack() as context_manager:
        if watcher is not None:
          context_manager.enter_context(watcher)
        if post_data is not None:
          response = session.post(url,
                                  data=post_data,
                                  headers=headers,
                                  timeout=HTTP_NORMAL_TIMEOUT_S,
                                  verify=verify)
        else:
          response = session.get(url,
                                 headers=headers,
                                 timeout=HTTP_NORMAL_TIMEOUT_S,
                                 verify=verify)
      break

    except requests.exceptions.SSLError:
      raise

    except (socket.timeout, requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
      logging.getLogger().warning("Querying '%s' failed (attempt %u/%u): %s %s" % (url,
                                                                                   attempt,
                                                                                   HTTP_MAX_ATTEMPTS,
                                                                                   e.__class__.__qualname__,
                                                                                   e))
      if attempt == HTTP_MAX_ATTEMPTS:
        raise

  response.raise_for_status()

  return response.content