Python requests.exceptions.ConnectionError() Examples

The following are 30 code examples of requests.exceptions.ConnectionError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests.exceptions , or try the search function .
Example #1
Source File: Struts2Scan.py    From Struts2-Scan with GNU General Public License v3.0 6 votes vote down vote up
def post_stream(url, data=None, headers=None, encoding='UTF-8', files=None):
    """分块接受数据"""
    try:
        lines = requests.post(url, data=data, headers=headers, timeout=_tiemout, stream=True, proxies=proxies,
                              files=None)
        html = list()
        for line in lines.iter_lines():
            line = line.decode(encoding)
            html.append(line.strip())
        return '\r\n'.join(html).strip()
    except ChunkedEncodingError as e:
        return '\r\n'.join(html).strip()
    except ConnectionError as e:
        return "ERROR:" + "HTTP连接错误"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP连接超时错误"
    except Exception as e:
        return 'ERROR:' + str(e) 
Example #2
Source File: events.py    From schemathesis with MIT License 6 votes vote down vote up
def from_exc(cls, exc: Exception) -> "InternalError":
        exception_type = f"{exc.__class__.__module__}.{exc.__class__.__qualname__}"
        if isinstance(exc, HTTPError):
            if exc.response.status_code == 404:
                message = f"Schema was not found at {exc.url}"
            else:
                message = f"Failed to load schema, code {exc.response.status_code} was returned from {exc.url}"
            return cls(message=message, exception_type=exception_type)
        exception = format_exception(exc)
        exception_with_traceback = format_exception(exc, include_traceback=True)
        if isinstance(exc, exceptions.ConnectionError):
            message = f"Failed to load schema from {exc.request.url}"
        else:
            message = "An internal error happened during a test run"
        return cls(
            message=message,
            exception_type=exception_type,
            exception=exception,
            exception_with_traceback=exception_with_traceback,
        ) 
Example #3
Source File: test_flask.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test(self):
        patience = 100
        while True:
            try:
                response = requests.get("http://localhost:{}".format(self.port))
                break
            except ConnectionError:
                patience -= 1
                if not patience:
                    self.fail(
                        "Couldn't get response from app, (Python executable {})".format(
                            sys.executable
                        )
                    )
                else:
                    sleep(0.1)

        self.assertIsInstance(response, Response)
        self.assertIn("Hello There!", response.text) 
Example #4
Source File: test_build.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_verify_tools_download_failure(build_command):
    "If the build tools can't be retrieved, the build fails"
    build_command.build_app = mock.MagicMock()
    build_command.download_url = mock.MagicMock(
        side_effect=requests_exceptions.ConnectionError
    )

    # Try to invoke the build
    with pytest.raises(BriefcaseCommandError):
        build_command()

    # The download was attempted
    build_command.download_url.assert_called_with(
        url='https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-wonky.AppImage',
        download_path=build_command.dot_briefcase_path / 'tools'
    )

    # But it failed, so the file won't be made executable...
    assert build_command.os.chmod.call_count == 0

    # and the command won't retain the downloaded filename.
    assert build_command.linuxdeploy_appimage != 'new-downloaded-file'

    # and no build will be attempted
    assert build_command.build_app.call_count == 0 
Example #5
Source File: test_verify_jdk.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_jdk_download_failure(test_command, tmp_path):
    "If an error occurs downloading the JDK, an error is raised"
    # Mock Linux as the host
    test_command.host_os = 'Linux'

    # Mock a failure on download
    test_command.download_url.side_effect = requests_exceptions.ConnectionError

    # Invoking verify_jdk causes a network failure.
    with pytest.raises(NetworkFailure):
        verify_jdk(command=test_command)

    # That download was attempted
    test_command.download_url.assert_called_with(
        url="https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/download/"
            "jdk8u242-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u242b08.tar.gz",
        download_path=tmp_path / "tools",
    )
    # No attempt was made to unpack the archive
    assert test_command.shutil.unpack_archive.call_count == 0 
Example #6
Source File: cassh_web.py    From cassh with Apache License 2.0 6 votes vote down vote up
def send(current_user=None):
    """
    CASSH add
    """
    pubkey = request.files['file']
    username = request.form['username']
    payload = {}
    payload.update({'realname': current_user['name'], 'password': current_user['password']})
    payload.update({'username': username})
    payload.update({'pubkey': pubkey.read().decode('UTF-8')})
    try:
        req = put(APP.config['CASSH_URL'] + '/client', \
                data=payload, \
                headers=APP.config['HEADERS'], \
                verify=False)
    except ConnectionError:
        return Response('Connection error : %s' % APP.config['CASSH_URL'])
    if 'Error' in req.text:
        return Response(req.text)
    return redirect('/status') 
Example #7
Source File: utils.py    From iquery with MIT License 6 votes vote down vote up
def requests_get(url, **kwargs):
    USER_AGENTS = (
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
        'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0',
        'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
        ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) '
         'Chrome/19.0.1084.46 Safari/536.5'),
        ('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46'
         'Safari/536.5')
    )
    try:
        r = requests.get(
            url,
            timeout=12,
            headers={'User-Agent': random.choice(USER_AGENTS)}, **kwargs
        )
    except ConnectionError:
        exit_after_echo('Network connection failed.')
    except Timeout:
        exit_after_echo('timeout.')
    return r 
Example #8
Source File: vimconn_openstack.py    From openmano with Apache License 2.0 6 votes vote down vote up
def get_tenant_list(self, filter_dict={}):
        '''Obtain tenants of VIM
        filter_dict can contain the following keys:
            name: filter by tenant name
            id: filter by tenant uuid/id
            <other VIM specific>
        Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
        '''
        self.logger.debug("Getting tenant from VIM filter: '%s'", str(filter_dict))
        try:
            self._reload_connection()
            tenant_class_list=self.keystone.tenants.findall(**filter_dict)
            tenant_list=[]
            for tenant in tenant_class_list:
                tenant_list.append(tenant.to_dict())
            return tenant_list
        except (ksExceptions.ConnectionError, ksExceptions.ClientException)  as e:
            self._format_exception(e) 
Example #9
Source File: vimconn_openstack.py    From openmano with Apache License 2.0 6 votes vote down vote up
def new_user(self, user_name, user_passwd, tenant_id=None):
        '''Adds a new user to openstack VIM'''
        '''Returns the user identifier'''
        self.logger.debug("osconnector: Adding a new user to VIM")
        try:
            self._reload_connection()
            user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
            #self.keystone.tenants.add_user(self.k_creds["username"], #role)
            return user.id
        except ksExceptions.ConnectionError as e:
            error_value=-vimconn.HTTP_Bad_Request
            error_text= type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0]))
        except ksExceptions.ClientException as e: #TODO remove
            error_value=-vimconn.HTTP_Bad_Request
            error_text= type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0]))
        #TODO insert exception vimconn.HTTP_Unauthorized
        #if reaching here is because an exception
        if self.debug:
            self.logger.debug("new_user " + error_text)
        return error_value, error_text 
Example #10
Source File: poll_pods.py    From social-relay with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_pod_relay_preferences(self, host):
        """Query remote pods on https first, fall back to http."""
        logging.info("Querying %s" % host)
        try:
            try:
                response = requests.get("https://%s/.well-known/x-social-relay" % host,
                                timeout=5,
                                headers={"User-Agent": config.USER_AGENT})
            except timeout:
                response = None
            if not response or response.status_code != 200:
                response = requests.get("http://%s/.well-known/x-social-relay" % host,
                                timeout=5,
                                headers={"User-Agent": config.USER_AGENT})
                if response.status_code != 200:
                    return None
        except (ConnectionError, Timeout, timeout):
            return None
        try:
            # Make sure we have a valid x-social-relay doc
            validate(response.json(), self.schema)
            return response.text
        except (ValueError, ValidationError):
            return None 
Example #11
Source File: jwauth.py    From pyArango with Apache License 2.0 6 votes vote down vote up
def __get_auth_token(self):
        request_data = '{"username":"%s","password":"%s"}' % (self.username, self.password)
        for connection_url in self.urls:
            try:
                response = self.session.post('%s/_open/auth' % connection_url, data=request_data)
                if response.ok:
                    json_data = response.content
                    if json_data:
                        data_dict = json_mod.loads(json_data.decode("utf-8"))
                        return data_dict.get('jwt')
            except requests_exceptions.ConnectionError:
                if connection_url is not self.urls[-1]:
                    logging.critical("Unable to connect to %s trying another", connection_url)
                else:
                    logging.critical("Unable to connect to any of the urls: %s", self.urls)
                    raise 
Example #12
Source File: test_units.py    From gphotos-sync with MIT License 6 votes vote down vote up
def test_download_timeout(self):
        a = auth.Authorize(scope, token_file, secrets_file)
        a.authorize()
        retry_error = False
        start = datetime.now()

        try:
            _ = a.session.get("https://httpbin.org//delay/5", stream=True, timeout=0.2)
        except exc.ConnectionError as e:
            retry_error = True
            print(e)

        elapsed = datetime.now() - start
        self.assertEqual(retry_error, True)
        # .2 timeout by 5 retries = 1 sec
        self.assertGreater(elapsed.seconds, 1) 
Example #13
Source File: struts2scan_api.py    From ParrotSecCN_Community_QQbot with GNU General Public License v2.0 6 votes vote down vote up
def get_302(url, headers=None, encoding='UTF-8'):
    """GET请求发送包装"""
    try:
        html = requests.get(url, headers=headers, proxies=proxies, timeout=_tiemout, allow_redirects=False)
        status_code = html.status_code
        if status_code == 302:
            html = html.headers.get("Location", "")
        elif status_code == 200:
            html = html.content.decode(encoding)
            html = html.replace('\x00', '').strip()
        else:
            html = ""
        return html
    except ConnectionError as e:
        return "ERROR:" + "HTTP连接错误"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP连接超时错误"
    except Exception as e:
        return 'ERROR:' + str(e) 
Example #14
Source File: struts2scan_api.py    From ParrotSecCN_Community_QQbot with GNU General Public License v2.0 6 votes vote down vote up
def get_stream(url, headers=None, encoding='UTF-8'):
    """分块接受数据"""
    try:
        lines = requests.get(url, headers=headers, timeout=_tiemout, stream=True, proxies=proxies)
        html = list()
        for line in lines.iter_lines():
            if b'\x00' in line:
                break
            line = line.decode(encoding)
            html.append(line.strip())
        return '\r\n'.join(html).strip()
    except ChunkedEncodingError as e:
        return '\r\n'.join(html).strip()
    except ConnectionError as e:
        return "ERROR:" + "HTTP连接错误"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP连接超时错误"
    except Exception as e:
        return 'ERROR:' + str(e) 
Example #15
Source File: Struts2Scan.py    From Struts2-Scan with GNU General Public License v3.0 6 votes vote down vote up
def get_302(url, headers=None, encoding='UTF-8'):
    """GET请求发送包装"""
    try:
        html = requests.get(url, headers=headers, proxies=proxies, timeout=_tiemout, allow_redirects=False)
        status_code = html.status_code
        if status_code == 302:
            html = html.headers.get("Location", "")
        elif status_code == 200:
            html = html.content.decode(encoding)
            html = html.replace('\x00', '').strip()
        else:
            html = ""
        return html
    except ConnectionError as e:
        return "ERROR:" + "HTTP连接错误"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP连接超时错误"
    except Exception as e:
        return 'ERROR:' + str(e) 
Example #16
Source File: vimconn_openstack.py    From openmano with Apache License 2.0 5 votes vote down vote up
def _format_exception(self, exception):
        '''Transform a keystone, nova, neutron  exception into a vimconn exception'''
        if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
                                  ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed,
                                  neClient.exceptions.ConnectionFailed)):
            raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))            
        elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException, 
                                    neExceptions.NeutronException, nvExceptions.BadRequest)):
            raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
        elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
            raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
        elif isinstance(exception, nvExceptions.Conflict):
            raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
        else: # ()
            raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception)) 
Example #17
Source File: vimconn_openstack.py    From openmano with Apache License 2.0 5 votes vote down vote up
def new_tenant(self, tenant_name, tenant_description):
        '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
        self.logger.debug("Adding a new tenant name: %s", tenant_name)
        try:
            self._reload_connection()
            tenant=self.keystone.tenants.create(tenant_name, tenant_description)
            return tenant.id
        except (ksExceptions.ConnectionError, ksExceptions.ClientException)  as e:
            self._format_exception(e) 
Example #18
Source File: hello_world.py    From IOTA_demo with MIT License 5 votes vote down vote up
def main(uri):
  # type: (Text) -> None
  api = StrictIota(uri)

  try:
    node_info = api.get_node_info()
  except ConnectionError as e:
    print("Hm.  {uri} isn't responding.  Is the node running?".format(uri=uri))
    print(e)
  except BadApiResponse as e:
    print("Looks like {uri} isn't very talkative today ):".format(uri=uri))
    print(e)
  else:
    print('Hello {uri}!'.format(uri=uri))
    pprint(node_info) 
Example #19
Source File: provider.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_sts_access(provider_resource_name):
    """Get for sts access."""
    # create an STS client
    sts_client = boto3.client("sts")

    credentials = dict()
    error_message = f"Unable to assume role with ARN {provider_resource_name}."
    try:
        # Call the assume_role method of the STSConnection object and pass the role
        # ARN and a role session name.
        assumed_role = sts_client.assume_role(RoleArn=provider_resource_name, RoleSessionName="AccountCreationSession")
        credentials = assumed_role.get("Credentials")
    except ParamValidationError as param_error:
        LOG.warn(msg=error_message)
        LOG.info(param_error)
        # We can't use the exc_info here because it will print
        # a traceback that gets picked up by sentry:
        # https://github.com/project-koku/koku/issues/1483
    except (ClientError, BotoConnectionError, NoCredentialsError) as boto_error:
        LOG.warn(msg=error_message, exc_info=boto_error)

    # return a kwargs-friendly format
    return dict(
        aws_access_key_id=credentials.get("AccessKeyId"),
        aws_secret_access_key=credentials.get("SecretAccessKey"),
        aws_session_token=credentials.get("SessionToken"),
    ) 
Example #20
Source File: test_app_apache.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def test_no_accessible_endpoint(self, *kwargs):
        c = ApacheContainerCrawler()
        with self.assertRaises(ConnectionError):
            c.crawl("mockcontainer") 
Example #21
Source File: test_app_nginx.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def test_no_accessible_endpoint(self, *arg):
        c = NginxContainerCrawler()
        with self.assertRaises(ConnectionError):
            c.crawl("mockcontainer") 
Example #22
Source File: test_app_liberty.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def test_none_liberty_container(self, *args):
        options = {"password": "password", "user": "liberty"}
        c = LibertyContainerCrawler()
        with self.assertRaises(ConnectionError):
            c.crawl(1234, **options) 
Example #23
Source File: test_app_tomcat.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def test_none_tomcat_container(self, *args):
        options = {"password": "password", "user": "tomcat"}
        c = TomcatContainerCrawler()
        with self.assertRaises(ConnectionError):
            c.crawl(1234, **options) 
Example #24
Source File: redis_host_crawler.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def crawl(self, root_dir='/', **kwargs):
        import pip
        pip.main(['install', 'redis'])
        import redis

        try:
            client = redis.Redis(host='localhost', port=self.default_port)
            metrics = client.info()
        except ConnectionError:
            logger.info("redis does not listen on port:%d", self.default_port)
            raise ConnectionError("no listen at %d", self.default_port)

        feature_attributes = feature.create_feature(metrics)

        return [(self.feature_key, feature_attributes, self.feature_type)] 
Example #25
Source File: redis_container_crawler.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def crawl(self, container_id=None, **kwargs):

        try:
            import redis
        except ImportError:
            import pip
            pip.main(['install', 'redis'])
            import redis

        # only crawl redis container. Otherwise, quit.
        c = dockercontainer.DockerContainer(container_id)
        port = self.get_port(c)

        if not port:
            return

        state = c.inspect['State']
        pid = str(state['Pid'])
        ips = run_as_another_namespace(
            pid, ['net'], utils.misc.get_host_ip4_addresses)

        for each_ip in ips:
            if each_ip != "127.0.0.1":
                ip = each_ip
                break

        client = redis.Redis(host=ip, port=port)

        try:
            metrics = client.info()
            feature_attributes = feature.create_feature(metrics)
            return [(self.feature_key, feature_attributes, self.feature_type)]
        except:
            logger.info("redis does not listen on port:%d", port)
            raise ConnectionError("no listen at %d", port) 
Example #26
Source File: resilientsession.py    From jira with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __recoverable(self, response, url, request, counter=1):
        msg = response
        if isinstance(response, ConnectionError):
            logging.warning(
                "Got ConnectionError [%s] errno:%s on %s %s\n%s\n%s"
                % (
                    response,
                    response.errno,
                    request,
                    url,
                    vars(response),
                    response.__dict__,
                )
            )
        if hasattr(response, "status_code"):
            if response.status_code in [502, 503, 504, 401]:
                # 401 UNAUTHORIZED still randomly returned by Atlassian Cloud as of 2017-01-16
                msg = "%s %s" % (response.status_code, response.reason)
                # 2019-07-25: Disabled recovery for codes above^
                return False
            elif not (
                response.status_code == 200
                and len(response.content) == 0
                and "X-Seraph-LoginReason" in response.headers
                and "AUTHENTICATED_FAILED" in response.headers["X-Seraph-LoginReason"]
            ):
                return False
            else:
                msg = "Atlassian's bug https://jira.atlassian.com/browse/JRA-41559"

        # Exponential backoff with full jitter.
        delay = min(60, 10 * 2 ** counter) * random.random()
        logging.warning(
            "Got recoverable error from %s %s, will retry [%s/%s] in %ss. Err: %s"
            % (request, url, counter, self.max_retries, delay, msg)
        )
        logging.debug("response.headers: %s", response.headers)
        logging.debug("response.body: %s", response.content)
        time.sleep(delay)
        return True 
Example #27
Source File: sqs.py    From lambda-webhook with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def deliver_message(self, message):
        body = json.loads(message['Body'])
        url = self.options.webhook_url or body.get('jenkins_url')
        if self.debug:
            print("Posting message to webhook.")
        for t in [0, 1, 2, 4, 8, 16]:
            time.sleep(t)
            try:
                response = requests.post(url, headers=body.get('headers'), data=body.get('data'))
                if self.debug:
                    print("Post result: {}".format(repr(response)))
                break
            except ConnectionError as e:
                print("ConnectionError: {}".format(e)) 
Example #28
Source File: serverleak.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def _get(url, timeout):
    try:
        response = requests.get(url, headers={
            'User-Agent': USER_AGENT
        }, timeout=timeout)
        return response
    except ConnectionError:
        return None 
Example #29
Source File: Struts2Scan.py    From Struts2-Scan with GNU General Public License v3.0 5 votes vote down vote up
def post(url, data=None, headers=None, encoding='UTF-8', files=None):
    """POST请求发送包装"""
    try:
        html = requests.post(url, data=data, headers=headers, proxies=proxies, timeout=_tiemout, files=files)
        html = html.content.decode(encoding)
        return html.replace('\x00', '').strip()
    except ChunkedEncodingError as e:
        html = post_stream(url, data, headers, encoding, files)
        return html
    except ConnectionError as e:
        return "ERROR:" + "HTTP连接错误"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP连接超时错误"
    except Exception as e:
        return 'ERROR:' + str(e) 
Example #30
Source File: Struts2Scan.py    From Struts2-Scan with GNU General Public License v3.0 5 votes vote down vote up
def get_stream(url, headers=None, encoding='UTF-8'):
    """分块接受数据"""
    try:
        lines = requests.get(url, headers=headers, timeout=_tiemout, stream=True, proxies=proxies)
        html = list()
        for line in lines.iter_lines():
            if b'\x00' in line:
                break
            line = line.decode(encoding)
            html.append(line.strip())
        return '\r\n'.join(html).strip()
    except ChunkedEncodingError as e:
        return '\r\n'.join(html).strip()
    except ConnectionError as e:
        return "ERROR:" + "HTTP连接错误"
    except ConnectTimeout as e:
        return "ERROR:" + "HTTP连接超时错误"
    except Exception as e:
        return 'ERROR:' + str(e)