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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #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: 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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #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}/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 #21
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 #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") 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 #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") 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 #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}/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 #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") 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}
Example #26
Source File: check_https.py From httpswatch with MIT License | 6 votes |
def check_http_page(info): http_redirect = info.new_check() try: resp, tree = fetch_through_redirects("http://{}".format(info.domain)) info.http_redirects_to_https = resp.url.startswith("https://") if info.http_redirects_to_https: http_redirect.succeed("HTTP site redirects to HTTPS.") else: http_redirect.fail("HTTP site doesn’t redirect to HTTPS.") except requests.Timeout: http_redirect.fail("The HTTP site times out.") return except requests.ConnectionError: http_redirect.fail("Nothing is listening on port 80") return except Not200 as e: http_redirect.fail("The HTTP site returns an error status ({}) on request.".format(e.status)) return
Example #27
Source File: selescrape.py From anime-downloader with The Unlicense | 6 votes |
def status_select(driver, url, status='hide'): ''' For now it doesnt do what its name suggests, I have planned to add a status reporter of the http response code. This part of the code is not removed because it is part of its core. Treat it like it isnt here. ''' try: if status == 'hide': driver.get(url) elif status == 'show': r = requests.head(url) if r.status_code == 503: raise RuntimeError("This website's sevice is unavailable or has cloudflare on.") driver.get(url) return r.status_code else: driver.get(url) except requests.ConnectionError: raise RuntimeError("Failed to establish a connection using the requests library.")
Example #28
Source File: api.py From lambda-chef-node-cleanup with Apache License 2.0 | 6 votes |
def request(self, method, path, headers={}, data=None): auth_headers = sign_request(key=self.key, http_method=method, path=self.parsed_url.path+path.split('?', 1)[0], body=data, host=self.parsed_url.netloc, timestamp=datetime.datetime.utcnow(), user_id=self.client) request_headers = {} request_headers.update(self.headers) request_headers.update(dict((k.lower(), v) for k, v in six.iteritems(headers))) request_headers['x-chef-version'] = self.version request_headers.update(auth_headers) try: response = self._request(method, self.url + path, data, dict( (k.capitalize(), v) for k, v in six.iteritems(request_headers))) except requests.ConnectionError as e: raise ChefServerError(e.message) if not response.ok: raise ChefServerError.from_error(response.reason, code=response.status_code) return response
Example #29
Source File: discovery.py From appr with Apache License 2.0 | 6 votes |
def discover_sources(package, version, media_type, secure=False): schemes = ["https://", "http://"] host, name = split_package_name(package) for scheme in schemes: url = scheme + host try: r = requests.get(url, params={"appr-discovery": 1}, timeout=2) except (requests.exceptions.Timeout, requests.ConnectionError) as e: if scheme == "https://" and not secure: continue else: raise e r.raise_for_status() variables = { 'name': name, 'version': version, "media_type": media_type, "mediatype": media_type} p = MetaHTMLParser(variables) p.feed(r.content.decode()) if package in p.meta: return p.meta[package] return None
Example #30
Source File: __init__.py From trainline-python with MIT License | 6 votes |
def _post(self, url, post_data, expected_status_code=200): trials = 0 while trials <= _MAX_SERVER_RETRY: trials += 1 ret = self.session.post(url=url, headers=self.headers, data=post_data) if (ret.status_code == expected_status_code): break else: time.sleep(_TIME_AFTER_FAILED_REQUEST) if (ret.status_code != expected_status_code): raise ConnectionError( 'Status code {status} for url {url}\n{content}'.format( status=ret.status_code, url=url, content=ret.text)) return ret