Python requests.ConnectTimeout() Examples

The following are 30 code examples of requests.ConnectTimeout(). 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 , or try the search function .
Example #1
Source File: down_html.py    From dayworkspace with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __call__(self):
        try:
            req = requests.get(self.url, headers=self.header,
                               timeout=10, proxies=self.proxies)
        except requests.ConnectTimeout or requests.exceptions.ReadTimeout as e:
            print(f"链接{self.url}已经超时")
            self.status = False
            return {"status": self.status, 'html': ''}
        try:
            encodeing = chardet.detect(req.content)['encoding']
            html = req.content.decode(encodeing, errors='replace')
        except Exception as e:
            print(e)
            print("编码时错误,具体错误不定......")
            self.status = False
            return {"status": self.status, 'html': ''}
        return {"status": self.status, 'html': html} 
Example #2
Source File: test_okta.py    From aws-okta-processor with MIT License 6 votes vote down vote up
def test_okta_connection_timeout(
            self,
            mock_print_tty,
            mock_makedirs,
            mock_open,
            mock_chmod
    ):
        responses.add(
            responses.POST,
            'https://organization.okta.com/api/v1/authn',
            body=ConnectTimeout()
        )

        with self.assertRaises(SystemExit):
            Okta(
                user_name="user_name",
                user_pass="user_pass",
                organization="organization.okta.com"
            )

        print_tty_calls = [
            call("Error: Timed Out")
        ]

        mock_print_tty.assert_has_calls(print_tty_calls) 
Example #3
Source File: test_utils.py    From civis-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_retry_multiple_exceptions():
    @retry((ConnectionError, ConnectTimeout), retries=4, delay=0.1)
    def raise_multiple_exceptions():
        counter['i'] += 1
        if counter['i'] == 1:
            raise ConnectionError('one error')
        elif counter['i'] == 2:
            raise ConnectTimeout('another error')
        else:
            return 'success'

    counter = dict(i=0)
    test_result = raise_multiple_exceptions()

    assert test_result == 'success'
    assert counter['i'] == 3 
Example #4
Source File: payments_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_payments_retry_doesnt_retry():
    fixture = helpers.load_fixture('payments')['retry']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.payments.retry(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #5
Source File: test_scoped_calls.py    From AnyAPI with MIT License 5 votes vote down vote up
def test_scoped_call():
    exception = []

    httpbin = AnyAPI(
        "http://httpbin.org",
        scoped_calls=[lambda request: parent_call(request, exception)],
    )
    httpbin.GET(timeout=1e-10)

    assert isinstance(exception[0], ConnectTimeout) 
Example #6
Source File: __init__.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def probe_wemo(host):
    """Probe a host for the current port.

    This probes a host for known-to-be-possible ports and
    returns the one currently in use. If no port is discovered
    then it returns None.
    """
    for port in PROBE_PORTS:
        try:
            r = requests.get('http://%s:%i/setup.xml' % (host, port),
                             timeout=10)
            if ('WeMo' in r.text) or ('Belkin' in r.text):
                return port
        except ConnectTimeout:
            # If we timed out connecting, then the wemo is gone,
            # no point in trying further.
            log.debug('Timed out connecting to %s on port %i, '
                      'wemo is offline', host, port)
            break
        except Timeout:
            # Apparently sometimes wemos get into a wedged state where
            # they still accept connections on an old port, but do not
            # respond. If that happens, we should keep searching.
            log.debug('No response from %s on port %i, continuing',
                      host, port)
            continue
        except ConnectionError:
            pass
    return None 
Example #7
Source File: module_helpers.py    From simplydomain with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request_json(self, url, return_code=200):
        """
        Request JSON content and expected return code.
        :param url:  URL to request
        :param return_code: expected return code or raise error
        :return: JSON, SuccessState
        """
        try:
            header = {
                'User-Agent': str(self.ua.google)
            }
            if not validators.url(url):
                self.print_yellow(
                    " [!] Invalid URL Requested: %s" % (str(url)))
                return {}, False
            r = requests.get(url, headers=header)
            if r.status_code != return_code:
                self.print_yellow(" [!] Request returned invalid status code: (CODE): %s (EXPECTED): %s" %
                                  (str(r.status_code), str(return_code)))
                return {}, False
            return r.content, True
        except requests.ConnectTimeout as e:
            self.print_red(
                " [!] Request ConnectionTimeout: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except requests.TooManyRedirects as e:
            self.print_red(
                " [!] Request TooManyRedirects: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except requests.HTTPError as e:
            self.print_red(
                " [!] Request TooManyRedirects: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except ConnectionError as e:
            self.print_red(
                " [!] Request ConnectionError: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except Exception as e:
            self.print_red(
                " [!] Request Unknown Error: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False 
Example #8
Source File: module_helpers.py    From simplydomain with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request_content(self, url, return_code=200):
        """
        Request content and expected return code.
        :param url:  URL to request
        :param return_code: expected return code or raise error
        :return: JSON, SuccessState
        """
        try:
            header = {
                'User-Agent': str(self.ua.google)
            }
            if not validators.url(url):
                self.print_yellow(
                    " [!] Invalid URL Requested: %s" % (str(url)))
                return {}, False
            r = requests.get(url, headers=header)
            if r.status_code != return_code:
                self.print_yellow(" [!] Request returned invalid status code: (CODE): %s (EXPECTED): %s" %
                                  (str(r.status_code), str(return_code)))
                return {}, False
            return r.content, True
        except requests.ConnectTimeout as e:
            self.print_red(
                " [!] Request ConnectionTimeout: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except requests.TooManyRedirects as e:
            self.print_red(
                " [!] Request TooManyRedirects: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except requests.HTTPError as e:
            self.print_red(
                " [!] Request TooManyRedirects: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except ConnectionError as e:
            self.print_red(
                " [!] Request ConnectionError: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except Exception as e:
            self.print_red(
                " [!] Request Unknown Error: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False 
Example #9
Source File: module_helpers.py    From simplydomain with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request_text(self, url, return_code=200):
        """
        Request content and expected return code.
        :param url:  URL to request
        :param return_code: expected return code or raise error
        :return: JSON, SuccessState
        """
        try:
            header = {
                'User-Agent': str(self.ua.google)
            }
            if not validators.url(url):
                self.print_yellow(
                    " [!] Invalid URL Requested: %s" % (str(url)))
                return {}, False
            r = requests.get(url, headers=header)
            if r.status_code != return_code:
                self.print_yellow(" [!] Request returned invalid status code: (CODE): %s (EXPECTED): %s" %
                                  (str(r.status_code), str(return_code)))
                return {}, False
            return r.text, True
        except requests.ConnectTimeout as e:
            self.print_red(
                " [!] Request ConnectionTimeout: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except requests.TooManyRedirects as e:
            self.print_red(
                " [!] Request TooManyRedirects: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except requests.HTTPError as e:
            self.print_red(
                " [!] Request TooManyRedirects: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except ConnectionError as e:
            self.print_red(
                " [!] Request ConnectionError: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except Exception as e:
            self.print_red(
                " [!] Request Unknown Error: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False 
Example #10
Source File: module_helpers.py    From simplydomain with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request_raw(self, url, return_code=200):
        """
        Request content and expected return code.
        :param url:  URL to request
        :param return_code: expected return code or raise error
        :return: JSON, SuccessState
        """
        try:
            header = {
                'User-Agent': str(self.ua.google)
            }
            if not validators.url(url):
                self.print_yellow(
                    " [!] Invalid URL Requested: %s" % (str(url)))
                return {}, False
            r = requests.get(url, headers=header)
            if r.status_code != return_code:
                self.print_yellow(" [!] Request returned invalid status code: (CODE): %s (EXPECTED): %s" %
                                  (str(r.status_code), str(return_code)))
                return {}, False
            return r, True
        except requests.ConnectTimeout as e:
            self.print_red(
                " [!] Request ConnectionTimeout: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except requests.TooManyRedirects as e:
            self.print_red(
                " [!] Request TooManyRedirects: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except requests.HTTPError as e:
            self.print_red(
                " [!] Request TooManyRedirects: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except ConnectionError as e:
            self.print_red(
                " [!] Request ConnectionError: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False
        except Exception as e:
            self.print_red(
                " [!] Request Unknown Error: (URL): %s (ERROR): %s" % (str(url), str(e)))
            return {}, False 
Example #11
Source File: creditor_bank_accounts_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_creditor_bank_accounts_disable_doesnt_retry():
    fixture = helpers.load_fixture('creditor_bank_accounts')['disable']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.creditor_bank_accounts.disable(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #12
Source File: customer_notifications_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_customer_notifications_handle_doesnt_retry():
    fixture = helpers.load_fixture('customer_notifications')['handle']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.customer_notifications.handle(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #13
Source File: customer_bank_accounts_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_customer_bank_accounts_disable_doesnt_retry():
    fixture = helpers.load_fixture('customer_bank_accounts')['disable']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.customer_bank_accounts.disable(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #14
Source File: mandates_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_mandates_cancel_doesnt_retry():
    fixture = helpers.load_fixture('mandates')['cancel']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.mandates.cancel(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #15
Source File: mandates_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_mandates_reinstate_doesnt_retry():
    fixture = helpers.load_fixture('mandates')['reinstate']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.mandates.reinstate(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #16
Source File: test_backend.py    From postmarker with MIT License 5 votes vote down vote up
def test_on_exception(self, catch_signal):
        with patch("requests.Session.request", side_effect=ConnectTimeout):
            with catch_signal(on_exception) as handler:
                send_mail(fail_silently=True, **SEND_KWARGS)
        assert handler.called
        kwargs = handler.call_args[1]
        assert kwargs["sender"] == EmailBackend
        assert kwargs["signal"] == on_exception
        assert isinstance(kwargs["exception"], ConnectTimeout)
        assert len(kwargs["raw_messages"]) == 1 
Example #17
Source File: mandate_imports_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_mandate_imports_submit_doesnt_retry():
    fixture = helpers.load_fixture('mandate_imports')['submit']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.mandate_imports.submit(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #18
Source File: mandate_imports_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_mandate_imports_cancel_doesnt_retry():
    fixture = helpers.load_fixture('mandate_imports')['cancel']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.mandate_imports.cancel(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #19
Source File: instalment_schedules_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_instalment_schedules_cancel_doesnt_retry():
    fixture = helpers.load_fixture('instalment_schedules')['cancel']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.instalment_schedules.cancel(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #20
Source File: redirect_flows_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_redirect_flows_complete_doesnt_retry():
    fixture = helpers.load_fixture('redirect_flows')['complete']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.redirect_flows.complete(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #21
Source File: subscriptions_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_subscriptions_pause_doesnt_retry():
    fixture = helpers.load_fixture('subscriptions')['pause']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.subscriptions.pause(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #22
Source File: subscriptions_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_subscriptions_resume_doesnt_retry():
    fixture = helpers.load_fixture('subscriptions')['resume']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.subscriptions.resume(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #23
Source File: subscriptions_integration_test.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def test_timeout_subscriptions_cancel_doesnt_retry():
    fixture = helpers.load_fixture('subscriptions')['cancel']
    with helpers.stub_timeout(fixture) as rsps:
      with assert_raises(requests.ConnectTimeout):
        response = helpers.client.subscriptions.cancel(*fixture['url_params'])
      assert_equal(1, len(rsps.calls)) 
Example #24
Source File: helpers.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def stub_timeout(resource_fixture):
    url_pattern = url_pattern_for(resource_fixture)
    json_body = json.dumps(resource_fixture['body'])
    with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps:
      rsps.add(resource_fixture['method'], url_pattern, body=ConnectTimeout())
      yield rsps
    # Will raise 'AssertionError: Not all requests have been executed'
    # if not all of the responses are hit. 
Example #25
Source File: helpers.py    From gocardless-pro-python with MIT License 5 votes vote down vote up
def stub_timeout_then_response(resource_fixture):
    url_pattern = url_pattern_for(resource_fixture)
    json_body = json.dumps(resource_fixture['body'])
    with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps:
      rsps.add(resource_fixture['method'], url_pattern, body=ConnectTimeout())
      rsps.add(resource_fixture['method'], url_pattern, body=json_body)
      yield rsps
    # Will raise 'AssertionError: Not all requests have been executed'
    # if not all of the responses are hit. 
Example #26
Source File: request.py    From jumpserver-python-sdk with GNU General Public License v2.0 5 votes vote down vote up
def do(self, api_name=None, pk=None, method='get', use_auth=True,
           data=None, params=None, content_type='application/json', **kwargs):

        if api_name in API_URL_MAPPING:
            path = API_URL_MAPPING.get(api_name)
            if pk and '%s' in path:
                path = path % pk
        else:
            path = api_name

        request_headers = kwargs.get('headers', {})
        default_headers = self.default_headers or {}
        headers = {k: v for k, v in default_headers.items()}
        headers.update(request_headers)
        kwargs['headers'] = headers
        url = self.endpoint.rstrip('/') + path
        req = HttpRequest(url, method=method, data=data,
                          params=params, content_type=content_type,
                          **kwargs)
        if use_auth:
            if not self.auth:
                msg = 'Authentication required, but not provide'
                logger.error(msg)
                raise RequestError(msg)
            else:
                self.auth.sign_request(req)

        try:
            resp = req.do()
        except (requests.ConnectionError, requests.ConnectTimeout) as e:
            msg = "Connect endpoint {} error: {}".format(self.endpoint, e)
            logger.error(msg)
            raise RequestError(msg)

        return self.clean_result(resp) 
Example #27
Source File: doc.py    From bot with MIT License 5 votes vote down vote up
def _fetch_inventory(self, inventory_url: str) -> Optional[dict]:
        """Get and return inventory from `inventory_url`. If fetching fails, return None."""
        fetch_func = functools.partial(intersphinx.fetch_inventory, SPHINX_MOCK_APP, '', inventory_url)
        for retry in range(1, FAILED_REQUEST_RETRY_AMOUNT+1):
            try:
                package = await self.bot.loop.run_in_executor(None, fetch_func)
            except ConnectTimeout:
                log.error(
                    f"Fetching of inventory {inventory_url} timed out,"
                    f" trying again. ({retry}/{FAILED_REQUEST_RETRY_AMOUNT})"
                )
            except ProtocolError:
                log.error(
                    f"Connection lost while fetching inventory {inventory_url},"
                    f" trying again. ({retry}/{FAILED_REQUEST_RETRY_AMOUNT})"
                )
            except HTTPError as e:
                log.error(f"Fetching of inventory {inventory_url} failed with status code {e.response.status_code}.")
                return None
            except ConnectionError:
                log.error(f"Couldn't establish connection to inventory {inventory_url}.")
                return None
            else:
                return package
        log.error(f"Fetching of inventory {inventory_url} failed.")
        return None 
Example #28
Source File: test_api.py    From pwned-passwords-django with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_timeout(self):
        """
        Connection timeouts to the API are handled gracefully.

        """
        request_mock = self._get_exception_mock(requests.ConnectTimeout())
        with mock.patch("requests.get", request_mock):
            result = api.pwned_password(self.sample_password)
            self.assertEqual(None, result) 
Example #29
Source File: okta.py    From aws-okta-processor with MIT License 5 votes vote down vote up
def call(self, endpoint=None, headers=None, json_payload=None):
        print_tty(
            "Info: Calling {}".format(endpoint),
            silent=self.silent
        )

        try:
            if json_payload is not None:
                return self.session.post(
                    endpoint,
                    json=json_payload,
                    headers=headers,
                    timeout=10
                )
            else:
                return self.session.get(
                    endpoint,
                    headers=headers,
                    timeout=10
                )

        except ConnectTimeout:
            print_tty("Error: Timed Out")
            sys.exit(1)

        except ConnectionError:
            print_tty("Error: Connection Error")
            sys.exit(1) 
Example #30
Source File: backend.py    From galaxy_blizzard_plugin with MIT License 5 votes vote down vote up
def do_request(self, method, url, data=None, json=True, headers=None, ignore_failure=False):
        loop = asyncio.get_event_loop()
        if not headers:
            headers = self._authentication_client.session.headers
        try:
            if data is None:
                data = {}
            params = {
                "method": method,
                "url": url,
                "data": data,
                "timeout": self._authentication_client.timeout,
                "headers": headers
            }
            try:
                response = await loop.run_in_executor(None, functools.partial(self._authentication_client.session.request, **params))
            except (requests.Timeout, requests.ConnectTimeout, requests.ReadTimeout):
                raise BackendTimeout()
            except requests.ConnectionError:
                raise NetworkError

            if not ignore_failure:
                self.handle_status_code(response.status_code)

            if json:
                return response.json()
            else:
                return response

        except Exception as e:
            raise e