Python requests.ConnectionError() Examples
The following are 30
code examples of requests.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
, or try the search function
.

Example #1
Source File: client.py From clashroyale with MIT License | 9 votes |
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
Example #2
Source File: verifyInsightCredentials.py From InsightAgent with Apache License 2.0 | 6 votes |
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)
Example #3
Source File: verifyInsightCredentials.py From InsightAgent with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: script_runner.py From InsightAgent with Apache License 2.0 | 6 votes |
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
Example #5
Source File: test.py From harmony-ops with MIT License | 6 votes |
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
Example #6
Source File: client.py From clashroyale with MIT License | 6 votes |
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
Example #7
Source File: api.py From zun with Apache License 2.0 | 6 votes |
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
Example #8
Source File: probe_search.py From ripe-atlas-tools with GNU General Public License v3.0 | 6 votes |
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()
Example #9
Source File: doc.py From bot with MIT License | 6 votes |
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
Example #10
Source File: Skeleton_Key.py From firmware_password_manager with MIT License | 6 votes |
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
Example #11
Source File: build_server.py From python-webpack with MIT License | 6 votes |
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 )
Example #12
Source File: watson.py From Watson with MIT License | 6 votes |
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']
Example #13
Source File: api.py From kuryr-kubernetes with Apache License 2.0 | 6 votes |
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
Example #14
Source File: DipperUtil.py From dipper with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #15
Source File: test_catalog.py From ideascube with GNU Affero General Public License v3.0 | 6 votes |
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 == {}
Example #16
Source File: main.py From rucio with Apache License 2.0 | 6 votes |
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))
Example #17
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): input_classification = params.get("classification") offset = params.get("offset") limit = params.get("limit") params = dict() if input_classification is not None: params["classification"] = input_classification params["offset"] = offset params["limit"] = limit try: response = self.connection.CLIENT.get(self.__URL, params=params) applications = response.json()["items"] applications = komand.helper.clean(applications) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: raise error return {"applications": applications}
Example #18
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): input_state = params.get("state") offset = params.get("offset") limit = params.get("limit") params = dict() if input_state is not None: params["state"] = input_state.upper() # CloudLock input is case-sensitive params["offset"] = offset params["limit"] = limit try: response = self.connection.CLIENT.get(self.__URL, params=params) policies = response.json() policies = komand.helper.clean(policies) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: raise error return {"policies": policies}
Example #19
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): name = params.get("name") q = params.get("q") offset = params.get("offset") limit = params.get("limit") params = dict() if name is not None: params["name"] = name if q is not None: params["q"] = q params["offset"] = offset params["limit"] = limit try: response = self.connection.CLIENT.get(self.__URL, params=params) entries = response.json()["items"] entries = komand.helper.clean(entries) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: raise error return {"entries": entries}
Example #20
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/tasks".format(org_id=org_id, inc_id=inc_id) self.logger.info("Retrieving tasks for incident %s..." % inc_id) try: response = self.connection.SESSION.get(url) tasks = response.json() tasks = komand.helper.clean(tasks) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"tasks": tasks}
Example #21
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") incident = params.get("incident") url = self.connection.API_BASE + "/orgs/{org_id}/incidents".format(org_id=org_id) incident = json.dumps(incident) self.logger.info("Creating incident for organization %s..." % org_id) try: response = self.connection.SESSION.post(url=url, data=incident) new_incident = response.json() new_incident = komand.helper.clean(new_incident) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"incident": new_incident}
Example #22
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/history".format(org_id=org_id, inc_id=inc_id) self.logger.info("Retrieving history for incident %s..." % inc_id) try: response = self.connection.SESSION.get(url) history = response.json() history = komand.helper.clean(history) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"incident_history": history}
Example #23
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}".format(org_id=org_id, inc_id=inc_id) self.logger.info("Retrieving incident %s..." % inc_id) try: response = self.connection.SESSION.get(url) incident = response.json() incident = komand.helper.clean(incident) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"incident": incident}
Example #24
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}".format(org_id=org_id, inc_id=inc_id) self.logger.info("Creating incident for organization %s..." % org_id) try: response = self.connection.SESSION.delete(url=url) status = response.json() status = komand.helper.clean(status) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"status": status}
Example #25
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts".format(org_id=org_id, inc_id=inc_id) self.logger.info("Retrieving artifacts for incident %s..." % inc_id) try: response = self.connection.SESSION.get(url) artifacts = response.json() artifacts = komand.helper.clean(artifacts) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"artifacts": artifacts}
Example #26
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") artifact_id = params.get("artifact_id") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts/{artifact_id}".format(org_id=org_id, inc_id=inc_id, artifact_id=artifact_id) self.logger.info("Retrieving artifact for incident %s..." % inc_id) try: response = self.connection.SESSION.get(url) artifact = response.json() artifact = komand.helper.clean(artifact) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"artifact": artifact}
Example #27
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") artifact = params.get("artifact") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts".format(org_id=org_id, inc_id=inc_id) artifact = json.dumps(artifact) self.logger.info("Creating artifact on incident %s..." % inc_id) try: response = self.connection.SESSION.post(url=url, data=artifact) new_artifact = response.json()[0] new_artifact = komand.helper.clean(new_artifact) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"artifact": new_artifact}
Example #28
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") patch = params.get("patch") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}".format(org_id=org_id, inc_id=inc_id) patch = json.dumps(patch) self.logger.info("Patching incident %s..." % inc_id) try: response = self.connection.SESSION.patch(url=url, data=patch) patch_status = response.json() patch_status = komand.helper.clean(patch_status) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"patch_status": patch_status}
Example #29
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/tasks".format(org_id=org_id, inc_id=inc_id) json_body = params.get("body") json_body = json.dumps(json_body) try: response = self.connection.SESSION.post(url=url, data=json_body) identifier = response.json()["id"] if response.status_code != 200: self.logger.error("Error occurred - check the JSON body and ensure the data is correct.") except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error %d: %s" % (response.status_code, error)) raise return {"identifier": identifier}
Example #30
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): org_id = params.get("organization_id") inc_id = params.get("incident_id") artifact_id = params.get("artifact_id") artifact = params.get("artifact") url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts/{artifact_id}".format(org_id=org_id, inc_id=inc_id, artifact_id=artifact_id) artifact = json.dumps(artifact) self.logger.info("Updating artifact %s..." % artifact_id) try: response = self.connection.SESSION.put(url=url, data=artifact) updated_artifact = response.json() updated_artifact = komand.helper.clean(updated_artifact) except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error: self.logger.error("Error: %s" % error) raise return {"artifact": updated_artifact}