Python requests.ConnectTimeout() Examples

The following are 30 code examples for showing how to use requests.ConnectTimeout(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module requests , or try the search function .

Example 1
Project: aws-okta-processor   Author: godaddy   File: test_okta.py    License: 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 2
Project: civis-python   Author: civisanalytics   File: test_utils.py    License: 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 3
Project: dayworkspace   Author: copie   File: down_html.py    License: 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 4
Project: jumpserver-python-sdk   Author: jumpserver   File: request.py    License: 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 5
Project: bot   Author: python-discord   File: doc.py    License: 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 6
Project: pwned-passwords-django   Author: ubernostrum   File: test_api.py    License: 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 7
Project: aws-okta-processor   Author: godaddy   File: okta.py    License: 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 8
Project: galaxy_blizzard_plugin   Author: bartok765   File: backend.py    License: 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 
Example 9
Project: oh-my-rss   Author: richshaw2015   File: wemp.py    License: MIT License 5 votes vote down vote up
def wemp_spider(url, site):
    """
    抓取微信内容
    :param url:
    :param site:
    :return:
    """
    if is_crawled_url(url):
        return

    try:
        rsp = requests.get(url, timeout=10)

        if rsp.ok:
            try:
                if get_host_name(rsp.url) == 'mp.weixin.qq.com':
                    title, author, content = parse_weixin_page(rsp)
                elif 'ershicimi.com' in get_host_name(rsp.url):
                    title, author, content = parse_ershicimi_page(rsp)
                else:
                    logger.warning(f'公众号域名解析异常:`{rsp.url}')
                    return
            except:
                logger.info(f'公众号内容解析异常:`{rsp.url}')
                return

            article = Article(title=title, author=author, site=site, uindex=current_ts(),
                              content=content, src_url=url)
            article.save()

            mark_crawled_url(url)
    except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):
        logger.warning(f'公众号爬取出现网络异常:`{url}')
    except:
        logger.warning(f'公众号爬取出现未知异常:`{url}') 
Example 10
Project: oh-my-rss   Author: richshaw2015   File: utils.py    License: MIT License 5 votes vote down vote up
def save_avatar(avatar, userid, size=100):
    """
    保存网络头像
    :param avatar:
    :param userid:
    :param size:
    :return: 保存后的头像地址
    """
    try:
        rsp = requests.get(avatar, timeout=10)

        if rsp.ok:
            img_obj = Image.open(BytesIO(rsp.content))
            img_obj.thumbnail((size, size))
            jpg = get_hash_name(userid) + '.jpg'

            if img_obj.mode != 'RGB':
                img_obj = img_obj.convert('RGB')

            img_obj.save(os.path.join(settings.BASE_DIR, 'assets', 'avatar', jpg))
            return f'/assets/avatar/{jpg}'
        else:
            logger.error(f"同步用户头像出现网络异常!`{userid}`{avatar}")
    except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):
        logger.error(f"同步用户头像网络异常!`{userid}`{avatar}")
    except:
        logger.error(f"同步用户头像未知异常`{userid}`{avatar}")

    return '/assets/img/logo.svg' 
Example 11
Project: visonic   Author: davesmeghead   File: client.py    License: Apache License 2.0 5 votes vote down vote up
def connect(self):
        # start of main function
        try:
            # Establish a callback to stop the component when the stop event occurs
            self.hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.stop_subscription)

            self.hass.services.async_register(DOMAIN, 'alarm_panel_reconnect', self.service_panel_reconnect)
            self.hass.services.async_register(DOMAIN, 'alarm_panel_eventlog', self.service_panel_eventlog, schema=ALARM_SERVICE_EVENTLOG)
            self.hass.services.async_register(DOMAIN, 'alarm_panel_command', self.service_panel_command, schema=ALARM_SERVICE_COMMAND)
            self.hass.services.async_register(DOMAIN, 'alarm_panel_download', self.service_panel_download)
                    
            success = self.connect_to_alarm()
            
            if success:
                # Create "alarm control panel"
                #   eventually there will be an "alarm control panel" for each partition but we only support 1 partition at the moment
                self.hass.async_create_task( self.hass.config_entries.async_forward_entry_setup(self.entry, "alarm_control_panel") )
                return True
            
        except (ConnectTimeout, HTTPError) as ex:
            _LOGGER.error("Unable to connect to Visonic Alarm Panel: %s", str(ex))
            hass.components.persistent_notification.create(
                'Error: {}<br />'
                'You will need to restart hass after fixing.'
                ''.format(ex),
                title=NOTIFICATION_TITLE,
                notification_id=NOTIFICATION_ID)
        
        return False 
Example 12
Project: cachet-url-monitor   Author: mtakaki   File: configuration.py    License: MIT License 5 votes vote down vote up
def evaluate(self):
        """Sends the request to the URL set in the configuration and executes
        each one of the expectations, one by one. The status will be updated
        according to the expectation results.
        """
        try:
            if self.endpoint_header is not None:
                self.request = requests.request(
                    self.endpoint_method, self.endpoint_url, timeout=self.endpoint_timeout, headers=self.endpoint_header
                )
            else:
                self.request = requests.request(self.endpoint_method, self.endpoint_url, timeout=self.endpoint_timeout)
            self.current_timestamp = int(time.time())
        except requests.ConnectionError:
            self.message = "The URL is unreachable: %s %s" % (self.endpoint_method, self.endpoint_url)
            self.logger.warning(self.message)
            self.status = st.ComponentStatus.PARTIAL_OUTAGE
            return
        except requests.HTTPError:
            self.message = "Unexpected HTTP response"
            self.logger.exception(self.message)
            self.status = st.ComponentStatus.PARTIAL_OUTAGE
            return
        except (requests.Timeout, requests.ConnectTimeout):
            self.message = "Request timed out"
            self.logger.warning(self.message)
            self.status = st.ComponentStatus.PERFORMANCE_ISSUES
            return

        # We initially assume the API is healthy.
        self.status = st.ComponentStatus.OPERATIONAL
        self.message = ""
        for expectation in self.expectations:
            status: ComponentStatus = expectation.get_status(self.request)

            # The greater the status is, the worse the state of the API is.
            if status.value > self.status.value:
                self.status = status
                self.message = expectation.get_message(self.request)
                self.logger.info(self.message) 
Example 13
Project: bilibili_member_crawler   Author: cwjokaka   File: worker.py    License: MIT License 5 votes vote down vote up
def _get_member_by_mid(self, mid: int) -> Optional[dict]:
        """
        根据用户id获取其信息
        :param mid: B站用户id
        :return: 用户详情 or None
        """
        get_params = {
            'mid': mid,
            'jsonp': 'jsonp'
        }
        try:
            res_json = requests.get(API_MEMBER_INFO, params=get_params, timeout=WAIT_MAX, proxies=self.cur_proxy,
                                    headers=self.headers).json()
        except ConnectTimeout as e:
            print(f'获取用户id: {mid} 详情失败: 请求接口超时, 当前代理:{self.cur_proxy["https"]}')
            raise RequestException(str(e))
        except ReadTimeout as e:
            print(f'获取用户id: {mid} 详情失败: 接口读取超时, 当前代理:{self.cur_proxy["https"]}')
            raise RequestException(str(e))
        except ValueError as e:
            # 解析json失败基本上就是ip被封了
            print(f'获取用户id: {mid} 详情失败: 解析json出错, 当前代理:{self.cur_proxy["https"]}')
            raise RequestException(str(e))
        except ProxyError as e:
            print(f'获取用户id: {mid} 详情失败: 连接代理失败, 当前代理:{self.cur_proxy["https"]}')
            raise RequestException(str(e))
        except requests.ConnectionError as e:
            # 可以断定就是代理IP地址无效
            print(f'获取用户id: {mid} 详情失败: 连接错误, 当前代理:{self.cur_proxy["https"]}')
            raise RequestException(str(e))
        except ChunkedEncodingError as e:
            print(f'获取用户id: {mid} 详情失败: 远程主机强迫关闭了一个现有的连接, 当前代理:{self.cur_proxy["https"]}')
            raise RequestException(str(e))
        else:
            if res_json['code'] == -404:
                print(f'找不到用户mid:{mid}')
                raise UserNotFoundException(f'找不到用户mid:{mid}')
            if 'data' in res_json:
                return res_json['data']
            print(f'获取用户id: {mid} 详情失败: data字段不存在!')
        return 
Example 14
Project: python-cloudant   Author: cloudant   File: client_tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_connect_timeout(self):
        """
        Test that a connect timeout occurs when instantiating
        a client object with a timeout of 10 ms.
        """
        with self.assertRaises(ConnectTimeout) as cm:
            self.set_up_client(auto_connect=True, timeout=.01)
        self.assertTrue(str(cm.exception).find('timed out.')) 
Example 15
Project: wikipron   Author: kylebgorman   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def can_connect_to_wiktionary() -> bool:
    """Check whether WAN connection to Wiktionary is available."""
    try:
        requests.get("https://en.wiktionary.org/wiki/linguistics")
    except (requests.ConnectionError, requests.ConnectTimeout):
        return False
    else:
        return True 
Example 16
def DomainScanner(domain):
    url = 'https://www.virustotal.com/vtapi/v2/url/scan'
    params = {'apikey': apikey, 'url': domain}

    # attempt connection to VT API and save response as r
    try:
        r = requests.post(url, params=params)
    except requests.ConnectTimeout as timeout:
        print('Connection timed out. Error is as follows-')
        print(timeout)

    # sanitize domain after upload for safety
    domainSani = domain.replace('.', '[.]')
    # handle ValueError response which may indicate an invalid key or an error with scan
    # if an except is raised, add the domain to a list for tracking purposes
    if r.status_code == 200:
        try:
            jsonResponse = r.json()
            # print error if the scan had an issue
            if jsonResponse['response_code'] is not 1:
                print('There was an error submitting the domain for scanning.')
                print(jsonResponse['verbose_msg'])
            elif jsonResponse['response_code'] == -2:
                print('{!s} is queued for scanning.'.format(domainSani))
                delay[domain] = 'queued'
            else:
                print('{!s} was scanned successfully.'.format(domainSani))

        except ValueError:
            print('There was an error when scanning {!s}. Adding domain to error list....'.format(domainSani))
            domainErrors.append(domain)

        # return domain errors for notifying user when script completes
        time.sleep(sleeptime)  ############### IF YOU HAVE A PRIVATE ACCESS YOU CAN CHANGE THIS TO 1 ###################
        return delay

    # API TOS issue handling
    elif r.status_code == 204:
        print('Received HTTP 204 response. You may have exceeded your API request quota or rate limit.')
        print('https://support.virustotal.com/hc/en-us/articles/115002118525-The-4-requests-minute-limitation-of-the-'
              'Public-API-is-too-low-for-me-how-can-I-have-access-to-a-higher-quota-') 
Example 17
Project: pipdate   Author: nschloe   File: main.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_pypi_version(name):
    import requests

    try:
        r = requests.get(f"https://pypi.org/pypi/{name}/json", timeout=1.0)
    except requests.ConnectTimeout:
        raise RuntimeError("GET requests time out.")
    except requests.ConnectionError:
        raise RuntimeError("Failed connection.")
    if not r.ok:
        raise RuntimeError(f"Response code {r.status_code} from pypi.org.")
    data = r.json()
    return data["info"]["version"] 
Example 18
Project: postmarker   Author: Stranger6667   File: test_backend.py    License: 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 19
Project: bazarr   Author: morpheus65535   File: check_update.py    License: GNU General Public License v3.0 5 votes vote down vote up
def updated(restart=True):
    if settings.general.getboolean('update_restart') and restart:
        try:
            requests.get('http://127.0.0.1:' + settings.general.port + settings.general.base_url + 'restart')
        except requests.ConnectionError:
            pass
        except (requests.ConnectTimeout, requests.HTTPError, requests.ReadTimeout, requests.Timeout):
            logging.info('BAZARR Restart failed, please restart Bazarr manually')
            updated(restart=False)
    else:
        database.execute("UPDATE system SET updated='1'") 
Example 20
Project: AnyAPI   Author: FKLC   File: test_scoped_calls.py    License: 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 21
Project: jarvis   Author: haynieresearch   File: __init__.py    License: 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 22
Project: simplydomain   Author: SimplySecurity   File: module_helpers.py    License: 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 23
Project: simplydomain   Author: SimplySecurity   File: module_helpers.py    License: 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 24
Project: simplydomain   Author: SimplySecurity   File: module_helpers.py    License: 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 25
Project: simplydomain   Author: SimplySecurity   File: module_helpers.py    License: 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 26
Project: gocardless-pro-python   Author: gocardless   File: creditor_bank_accounts_integration_test.py    License: 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 27
Project: gocardless-pro-python   Author: gocardless   File: customer_notifications_integration_test.py    License: 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 28
Project: gocardless-pro-python   Author: gocardless   File: customer_bank_accounts_integration_test.py    License: 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 29
Project: gocardless-pro-python   Author: gocardless   File: mandates_integration_test.py    License: 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 30
Project: gocardless-pro-python   Author: gocardless   File: mandates_integration_test.py    License: 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))