当前位置: 首页>>代码示例>>Python>>正文


Python requests.ConnectionError方法代码示例

本文整理汇总了Python中requests.ConnectionError方法的典型用法代码示例。如果您正苦于以下问题:Python requests.ConnectionError方法的具体用法?Python requests.ConnectionError怎么用?Python requests.ConnectionError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在requests的用法示例。


在下文中一共展示了requests.ConnectionError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sendData

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def sendData():
    global projectName
    global userInsightfinder
    global licenseKey
    alldata["userName"] = userInsightfinder
    alldata["operation"] = "verify"
    alldata["licenseKey"] = licenseKey
    alldata["projectName"] = projectName
    json_data = json.dumps(alldata)
    #print json_data
    url = serverUrl + "/api/v1/agentdatahelper"
    print serverUrl
    try:
        response = requests.post(url, data = json.loads(json_data))
    except requests.ConnectionError, e:
        print "Connection failure : " + str(e)
        print "Verification with InsightFinder credentials Failed"
        sys.exit(1) 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:20,代码来源:verifyInsightCredentials.py

示例2: verifyUser

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def verifyUser(username, licenseKey, projectName):
    alldata = {}
    alldata["userName"] = username
    alldata["operation"] = "verify"
    alldata["licenseKey"] = licenseKey
    alldata["projectName"] = projectName
    toSendDataJSON = json.dumps(alldata)

    url = parameters['serverUrl'] + "/api/v1/agentdatahelper"

    try:
        response = requests.post(url, data=json.loads(toSendDataJSON))
    except requests.ConnectionError, e:
        logger.error("Connection failure : " + str(e))
        logger.error("Verification with InsightFinder credentials Failed")
        return False 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:18,代码来源:script_runner.py

示例3: is_after_epoch

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def is_after_epoch(n):
    url = args.hmy_endpoint_src
    payload = """{
        "jsonrpc": "2.0",
        "method": "hmy_latestHeader",
        "params": [  ],
        "id": 1
    }"""
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request('POST', url, headers=headers, data=payload, allow_redirects=False, timeout=3)
        body = json.loads(response.content)
        return int(body["result"]["epoch"]) > n
    except (requests.ConnectionError, KeyError):
        return False 
开发者ID:harmony-one,项目名称:harmony-ops,代码行数:19,代码来源:test.py

示例4: _request

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def _request(self, url, refresh=False, **params):
        if self.using_cache and refresh is False:  # refresh=True forces a request instead of using cache
            cache = self._resolve_cache(url, **params)
            if cache is not None:
                return cache
        method = params.get('method', 'GET')
        json_data = params.get('json', {})
        timeout = params.pop('timeout', None) or self.timeout
        if self.is_async:  # return a coroutine
            return self._arequest(url, **params)
        try:
            with self.session.request(
                method, url, timeout=timeout, headers=self.headers, params=params, json=json_data
            ) as resp:
                return self._raise_for_status(resp, resp.text, method=method)
        except requests.Timeout:
            raise NotResponding
        except requests.ConnectionError:
            raise NetworkError 
开发者ID:cgrok,项目名称:clashroyale,代码行数:21,代码来源:client.py

示例5: _request

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def _request(self, url, refresh=False, **params):
        if self.using_cache and refresh is False:  # refresh=True forces a request instead of using cache
            cache = self._resolve_cache(url, **params)
            if cache is not None:
                return cache
        if self.ratelimit[1] == 0 and time() < self.ratelimit[2] / 1000:
            if not url.endswith('/auth/stats'):
                raise RatelimitErrorDetected(self.ratelimit[2] / 1000 - time())
        if self.is_async:  # return a coroutine
            return self._arequest(url, **params)
        timeout = params.pop('timeout', None) or self.timeout
        try:
            with self.session.get(url, timeout=timeout, headers=self.headers, params=params) as resp:
                return self._raise_for_status(resp, resp.text, method='GET')
        except requests.Timeout:
            raise NotResponding
        except requests.ConnectionError:
            raise NetworkError 
开发者ID:cgrok,项目名称:clashroyale,代码行数:20,代码来源:client.py

示例6: _make_request

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def _make_request(self, path, cni_envs, expected_status=None):
        method = 'POST'

        host = CONF.cni_daemon.cni_daemon_host
        port = CONF.cni_daemon.cni_daemon_port
        url = 'http://%s:%s/%s' % (host, port, path)
        try:
            LOG.debug('Making request to CNI Daemon. %(method)s %(path)s\n'
                      '%(body)s',
                      {'method': method, 'path': url, 'body': cni_envs})
            resp = requests.post(url, json=cni_envs,
                                 headers={'Connection': 'close'})
        except requests.ConnectionError:
            LOG.exception('Looks like %s:%s cannot be reached. '
                          'Is zun-cni-daemon running?', (host, port))
            raise
        LOG.debug('CNI Daemon returned "%(status)d %(reason)s".',
                  {'status': resp.status_code, 'reason': resp.reason})
        if expected_status and resp.status_code != expected_status:
            LOG.error('CNI daemon returned error "%(status)d %(reason)s".',
                      {'status': resp.status_code, 'reason': resp.reason})
            raise exception.CNIError('Got invalid status code from CNI daemon')
        return resp 
开发者ID:openstack,项目名称:zun,代码行数:25,代码来源:api.py

示例7: test_location_google_breaks

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def test_location_google_breaks(self):
        """User passed location arg but google api gave error"""
        caught_exceptions = [
            requests.ConnectionError, requests.HTTPError, requests.Timeout]
        with mock.patch('requests.get') as mock_get:
            for exception in caught_exceptions:
                mock_get.side_effect = exception
                with capture_sys_output():
                    with self.assertRaises(RipeAtlasToolsException):
                        cmd = Command()
                        cmd.init_args(["--location", "blaaaa"])
                        cmd.run()
            mock_get.side_effect = Exception()
            with self.assertRaises(Exception):
                cmd = Command()
                cmd.init_args(["--location", "blaaaa"])
                cmd.run() 
开发者ID:RIPE-NCC,项目名称:ripe-atlas-tools,代码行数:19,代码来源:probe_search.py

示例8: convert

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def convert(ctx: commands.Context, url: str) -> str:
        """Convert url to Intersphinx inventory URL."""
        try:
            intersphinx.fetch_inventory(SPHINX_MOCK_APP, '', url)
        except AttributeError:
            raise commands.BadArgument(f"Failed to fetch Intersphinx inventory from URL `{url}`.")
        except ConnectionError:
            if url.startswith('https'):
                raise commands.BadArgument(
                    f"Cannot establish a connection to `{url}`. Does it support HTTPS?"
                )
            raise commands.BadArgument(f"Cannot connect to host with URL `{url}`.")
        except ValueError:
            raise commands.BadArgument(
                f"Failed to read Intersphinx inventory from URL `{url}`. "
                "Are you sure that it's a valid inventory file?"
            )
        return url 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:doc.py

示例9: verify_network

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def verify_network(self):
        """
        Verifies network availability.

        Host: 8.8.8.8 (google-public-dns-a.google.com)
        OpenPort: 53/tcp
        Service: domain (DNS/TCP)
        """

        try:
            _ = requests.get("https://dns.google.com", timeout=3)
            # _ = requests.get("https://8.8.8.8", timeout=3)
            return True
        except requests.ConnectionError as exception_message:
            self.logger.error("%s: Unknown error. [%s]" % (inspect.stack()[0][3], exception_message))
        return False 
开发者ID:univ-of-utah-marriott-library-apple,项目名称:firmware_password_manager,代码行数:18,代码来源:Skeleton_Key.py

示例10: is_running

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def is_running(self, debug=False):
        try:
            res = requests.post(self.url)
        except requests.ConnectionError:
            if debug:
                print('connection error')
            return False

        if debug:
            print('res', 'static_code', res.status_code, 'text', res.text)

        # Hacky, but it works for now
        return (
            res.status_code == 200 and
            'webpack-build' in res.text and
            'Config file not defined' in res.text
        ) 
开发者ID:markfinger,项目名称:python-webpack,代码行数:19,代码来源:build_server.py

示例11: _get_remote_projects

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def _get_remote_projects(self):
        # import when required in order to reduce watson response time (#312)
        import requests
        if not hasattr(self, '_remote_projects'):
            dest, headers = self._get_request_info('projects')

            try:
                response = requests.get(dest, headers=headers)
                assert response.status_code == 200

                self._remote_projects = response.json()
            except requests.ConnectionError:
                raise WatsonError("Unable to reach the server.")
            except AssertionError:
                raise WatsonError(
                    u"An error occurred with the remote "
                    "server: {}".format(response.json())
                )

        return self._remote_projects['projects'] 
开发者ID:TailorDev,项目名称:Watson,代码行数:22,代码来源:watson.py

示例12: _make_request

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def _make_request(self, path, cni_envs, expected_status=None):
        method = 'POST'

        address = config.CONF.cni_daemon.bind_address
        url = 'http://%s/%s' % (address, path)
        try:
            LOG.debug('Making request to CNI Daemon. %(method)s %(path)s\n'
                      '%(body)s',
                      {'method': method, 'path': url, 'body': cni_envs})
            resp = requests.post(url, json=cni_envs,
                                 headers={'Connection': 'close'})
        except requests.ConnectionError:
            LOG.exception('Looks like %s cannot be reached. Is kuryr-daemon '
                          'running?', address)
            raise
        LOG.debug('CNI Daemon returned "%(status)d %(reason)s".',
                  {'status': resp.status_code, 'reason': resp.reason})
        if expected_status and resp.status_code != expected_status:
            LOG.error('CNI daemon returned error "%(status)d %(reason)s".',
                      {'status': resp.status_code, 'reason': resp.reason})
            raise k_exc.CNIError('Got invalid status code from CNI daemon.')
        return resp 
开发者ID:openstack,项目名称:kuryr-kubernetes,代码行数:24,代码来源:api.py

示例13: get_hgnc_id_from_symbol

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def get_hgnc_id_from_symbol(gene_symbol):
        """
        Get HGNC curie from symbol using monarch and mygene services
        :param gene_symbol:
        :return:
        """
        monarch_url = 'https://solr.monarchinitiative.org/solr/search/select'
        params = DipperUtil._get_solr_weight_settings()
        params["q"] = "{0} \"{0}\"".format(gene_symbol)
        params["fq"] = ["taxon:\"NCBITaxon:9606\"", "category:\"gene\""]
        gene_id = None
        try:
            monarch_request = requests.get(monarch_url, params=params)
            response = monarch_request.json()
            count = response['response']['numFound']
            if count > 0:
                gene_id = response['response']['docs'][0]['id']
        except requests.ConnectionError:
            print("error fetching {0}".format(monarch_url))

        return gene_id 
开发者ID:monarch-initiative,项目名称:dipper,代码行数:23,代码来源:DipperUtil.py

示例14: test_catalog_update_cache_no_fail_if_remote_unavailable

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def test_catalog_update_cache_no_fail_if_remote_unavailable(mocker):
    from ideascube.serveradmin.catalog import Catalog
    from requests import ConnectionError

    mocker.patch('ideascube.serveradmin.catalog.urlretrieve',
                 side_effect=ConnectionError)

    c = Catalog()
    assert c._available == {}
    assert c._installed == {}

    c.add_remote(
        'foo', 'Content from Foo', 'http://example.com/not_existing')
    c.update_cache()
    assert c._available == {}
    assert c._installed == {} 
开发者ID:ideascube,项目名称:ideascube,代码行数:18,代码来源:test_catalog.py

示例15: GET

# 需要导入模块: import requests [as 别名]
# 或者: from requests import ConnectionError [as 别名]
def GET(self):
        try:
            data = param_input()
            response = get(str(data.file_location), cert=config_get('webui', 'usercert'), verify=False)
            if not response.ok:
                response.raise_for_status()
            cont = response.content
            file_like_object = BytesIO(cont)
            tar = open(mode='r:gz', fileobj=file_like_object)
            jsonResponse = {}
            for member in tar.getmembers():
                jsonResponse[member.name] = member.size
            header('Content-Type', 'application/json')
            return dumps(jsonResponse)
        except ConnectionError as err:
            raise generate_http_error(503, str(type(err)), str(err))
        except TarError as err:
            raise generate_http_error(415, str(type(err)), str(err))
        except IOError as err:
            raise generate_http_error(422, str(type(err)), str(err))
        except Exception as err:
            raise generate_http_error(500, str(type(err)), str(err)) 
开发者ID:rucio,项目名称:rucio,代码行数:24,代码来源:main.py


注:本文中的requests.ConnectionError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。