Here are the examples of the python api requests.ConnectionError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
134 Examples
5
Example 1
Project: heat Source File: test_nova_client.py
def test_absolute_limits_failure(self):
limits = mock.Mock()
limits.absolute = self._absolute_limits()
self.nova_client.limits.get.side_effect = [
requests.ConnectionError, requests.ConnectionError,
requests.ConnectionError]
self.assertRaises(requests.ConnectionError,
self.nova_plugin.absolute_limits)
3
Example 2
def get_profile(self, member_id=None, member_url=None, selectors=None,
params=None, headers=None):
if member_id:
url = '%s/id=%s' % (ENDPOINTS.PEOPLE, str(member_id))
elif member_url:
url = '%s/url=%s' % (ENDPOINTS.PEOPLE, urllib.quote_plus(member_url))
else:
url = '%s/~' % ENDPOINTS.PEOPLE
if selectors:
url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors))
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 3
def request(self, host, handler, request_body, verbose=0):
# Retry request once if cached connection has gone cold
for i in (0, 1):
try:
return self.single_request(host, handler, request_body, verbose)
except requests.ConnectionError:
if i:
raise
except requests.Timeout:
if i:
raise
3
Example 4
def http_get(self, url, params=None):
"""Make a HTTP request for the URL.
:param str url: The URL to request
:param dict params: Get query string parameters
"""
kwargs = {'url': url,
'auth': (self.config.get('username', self.DEFAULT_USER),
self.config.get('password', self.DEFAULT_PASSWORD)),
'verify': self.config.get('verify_ssl_cert', True)}
if params:
kwargs['params'] = params
try:
return self.requests_session.get(**kwargs)
except requests.ConnectionError as error:
LOGGER.error('Error fetching data from %s: %s', url, error)
return None
3
Example 5
Project: gae-boilerplate Source File: linkedin.py
def get_job_bookmarks(self, selectors=None, params=None, headers=None):
url = '%s/~/job-bookmarks' % ENDPOINTS.PEOPLE
if selectors:
url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors))
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 6
Project: caniusepython3 Source File: __init__.py
def skip_pypi_timeouts(method):
@functools.wraps(method)
def closure(*args, **kwargs):
try:
method(*args, **kwargs)
except requests.ConnectionError as exc:
raise unittest.SkipTest('PyPI had an error:' + str(exc))
return closure
3
Example 7
def request(self, url='', method='GET', params=None, data=None, files=None, verify=None, allow_redirects=True):
try:
response = self.session.request(
method=method,
url=url,
params=params,
data=data,
files=files,
verify=verify,
allow_redirects=allow_redirects,
)
except requests.ConnectionError as e:
msg = 'Could not connect to {site}: {error}'
raise ImageHostError(msg.format(site=self, error=e))
return response
3
Example 8
Project: cameo Source File: webmodels.py
def load_webmodel(query, solver_interface, sanitize=True):
logger.debug('Querying webmodels ... trying http://bigg.ucsd.edu first')
try:
model = get_model_from_bigg(query, solver_interface=solver_interface, sanitize=sanitize)
except Exception:
logger.debug('Querying webmodels ... trying minho next')
try:
df = index_models_minho()
except requests.ConnectionError as e:
logger.error("You need to be connected to the internet to load an online model.")
raise e
except Exception as e:
logger.error("Something went wrong while looking up available webmodels.")
raise e
try:
model = get_model_from_uminho(query, df, solver_interface=solver_interface, sanitize=sanitize)
except IndexError:
raise ValueError("%s is neither a file nor a model ID." % query)
return model
3
Example 9
def test_index(self):
try:
index = index_models_minho()
except requests.ConnectionError:
raise SkipTest('skipping web test due to connection error')
self.assertIsInstance(index, DataFrame)
self.assertListEqual(list(index.columns),
["id", "name", "doi", "author", "year", "formats", "organism", "taxonomy", "validated"])
3
Example 10
def get_group(self, group_id, selectors=None, params=None, headers=None):
url = '%s/%s' % (ENDPOINTS.GROUPS, str(group_id))
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 11
def join_group(self, group_id):
url = '%s/~/group-memberships/%s' % (ENDPOINTS.PEOPLE, str(group_id))
try:
response = self.make_request('PUT', url,
data=json.dumps({'membershipState': {'code': 'member'}}))
response.raise_for_status()
except (requests.ConnectionError, requests.HTTPError), error:
raise LinkedInHTTPError(error.message)
else:
return True
3
Example 12
def search_company(self, selectors=None, params=None, headers=None):
url = ENDPOINTS.COMPANY_SEARCH
if selectors:
url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors))
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 13
@retry_on_exception_exponential_backoff(exceptions=(requests.ConnectionError,))
def put(self, *args, **kwargs):
"""
Send a PUT request to a url. Arguments to this method, unless otherwise docuemented below in _request(), are
exactly the same as arguments to session.put() in the requests library.
:rtype: requests.Response
"""
return self._request('PUT', *args, **kwargs)
3
Example 14
def get_network_status(self, params=None, headers=None):
url = '%s/~/network/network-stats' % ENDPOINTS.PEOPLE
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 15
Project: wercker-cli Source File: metrics.py
def track_application_startup():
try:
command = default_command_name
arguments = None
if len(sys.argv) >= 2:
command = sys.argv[1]
if len(sys.argv) >= 3:
arguments = sys.argv[2:]
track_command_usage(command, arguments)
except requests.ConnectionError, requests.HTTPError:
pass
3
Example 16
Project: grr Source File: comms_test.py
def testConnectionErrorRecovery(self):
instrumentor = RequestsInstrumentor()
# When we can't connect at all (server not listening), we get a
# requests.exceptions.ConnectionError but the response object is None.
err_response = requests.ConnectionError("Error", response=None)
instrumentor.responses = [err_response, _make_200("Good")]
with instrumentor.instrument():
manager = MockHTTPManager()
result = manager.OpenServerEndpoint("control")
self.assertEqual(result.data, "Good")
3
Example 17
Project: teuthology Source File: test_pcp.py
@patch('os.makedirs')
@patch('teuthology.task.pcp.GrafanaGrapher')
@patch('teuthology.task.pcp.GraphiteGrapher')
def test_end_16049(self, m_grafana, m_graphite, m_makedirs):
# http://tracker.ceph.com/issues/16049
# Jobs were failing if graph downloading failed. We don't want that.
self.ctx.archive = '/fake/path'
with self.klass(self.ctx, self.task_config) as task:
task.graphite.download_graphs.side_effect = \
requests.ConnectionError
# Even though downloading graphs failed, we should have called
# write_html() a second time, again with no args
assert task.graphite.write_html.call_args_list == [call(), call()]
assert isinstance(task.stop_time, int)
3
Example 18
Project: hamms Source File: test_endpoints.py
def test_5511():
# Would need to wait 5 seconds to assert anything about this.
with assert_raises(requests.ConnectionError) as cm:
url = 'http://127.0.0.1:{port}?size={size}'.format(port=BASE_PORT+11,
size=1024*64)
r = requests.get(url)
assert_is_instance(cm.exception.message[1], LineTooLong)
url = 'http://127.0.0.1:{port}'.format(port=BASE_PORT+11)
r = requests.get(url)
assert_equal(len(r.headers['Cookie']), 1024*63)
3
Example 19
Project: JDong Source File: dama.py
def get_left_point(self):
try:
r = self.s.post('http://apib.sz789.net:88/GetUserInfo.ashx', self.data)
return r.json()
except requests.ConnectionError:
return self.get_left_point()
except:
return False
3
Example 20
Project: rtv Source File: test_objects.py
@pytest.mark.parametrize('use_ascii', [True, False])
def test_objects_load_screen_nested(terminal, use_ascii):
terminal.config['ascii'] = use_ascii
with terminal.loader(message='Outer'):
with terminal.loader(message='Inner'):
raise requests.ConnectionError()
assert False # Should never be reached
assert isinstance(terminal.loader.exception, requests.ConnectionError)
assert terminal.loader.depth == 0
assert not terminal.loader._is_running
assert not terminal.loader._animator.is_alive()
3
Example 21
def _index_models(self):
try:
self._index = self._index_method()
except requests.ConnectionError:
self._index = ["no_models_available"]
self.no_models_available = "The server could not be reached. Make sure you are connected to the internet"
3
Example 22
def get_posts(self, group_id, post_ids=None, selectors=None, params=None,
headers=None):
url = '%s/%s/posts' % (ENDPOINTS.GROUPS, str(group_id))
if post_ids:
url = '%s::(%s)' % (url, ','.join(map(str, post_ids)))
if selectors:
url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors))
try:
response = self.make_request('GET', url, params=params, headers=headers)
if response.content:
response = response.json()
else:
return None
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 23
Project: JDong Source File: dama.py
def recv_byte(self, imgdata):
self.data['imgdata'] = binascii.b2a_hex(imgdata).upper()
try:
r = self.s.post('http://apib.sz789.net:88/RecvByte.ashx', self.data)
res = r.json()
if res[u'info'] == -1:
self.report_err(res[u'imgid']) # 识别错误
return False
return r.json()[u'result']
except requests.ConnectionError:
return self.recv_byte(imgdata)
except:
return False
3
Example 24
Project: cameo Source File: test_webmodels.py
def test_get_sbml(self):
try:
tmp = get_sbml_file(1)
except requests.ConnectionError:
raise SkipTest('skipping web test due to connection error')
self.assertIsInstance(tmp, _TemporaryFileWrapper)
self.assertRaises(NotFoundException, get_sbml_file, -1)
3
Example 25
def leave_group(self, group_id):
url = '%s/~/group-memberships/%s' % (ENDPOINTS.PEOPLE, str(group_id))
try:
response = self.make_request('DELETE', url)
response.raise_for_status()
except (requests.ConnectionError, requests.HTTPError), error:
raise LinkedInHTTPError(error.message)
else:
return True
3
Example 26
Project: gae-boilerplate Source File: linkedin.py
def get_company_updates(self, company_id, params=None, headers=None):
url = '%s/%s/updates' % (ENDPOINTS.COMPANIES, str(company_id))
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 27
Project: gae-boilerplate Source File: linkedin.py
def unfollow_company(self, company_id):
url = '%s/~/following/companies/id=%s' % (ENDPOINTS.PEOPLE, str(company_id))
try:
response = self.make_request('DELETE', url)
response.raise_for_status()
except (requests.ConnectionError, requests.HTTPError), error:
raise LinkedInHTTPError(error.message)
else:
return True
3
Example 28
@retry_on_exception_exponential_backoff(exceptions=(requests.ConnectionError,))
def post(self, *args, **kwargs):
"""
Send a POST request to a url. Arguments to this method, unless otherwise docuemented below in _request(), are
exactly the same as arguments to session.post() in the requests library.
:rtype: requests.Response
"""
return self._request('POST', *args, **kwargs)
3
Example 29
def get_job(self, job_id, selectors=None, params=None, headers=None):
url = '%s/%s' % (ENDPOINTS.JOBS, str(job_id))
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 30
Project: freight_forwarder Source File: registry_base.py
@utils.retry
def _request_builder(self, verb, path, body={}, headers={}, params={}):
url = "{0}{1}/{2}/{3}".format(self.scheme, self.location, self.api_version, path)
headers_values = headers if headers else {'Accept': 'application/json', 'Content-Type': 'application/json'}
verb = verb.upper()
try:
if verb in ('PUT', 'PATCH', 'POST'):
response = self.session.request(verb, url, data=body, headers=headers_values, params=params)
else:
response = self.session.request(verb, url, headers=headers_values, params=params)
except requests.ConnectionError:
# TODO: need up raise more Registry specific exceptions
raise
return response
3
Example 31
def search_job(self, selectors=None, params=None, headers=None):
url = ENDPOINTS.JOB_SEARCH
if selectors:
url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors))
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 32
Project: ClusterRunner Source File: functional_test_cluster.py
def _is_url_responsive(self, url):
is_responsive = False
with suppress(requests.ConnectionError):
resp = requests.get(url)
if resp and resp.ok:
is_responsive = True
return is_responsive
3
Example 33
def send_invitation(self, invitation):
assert type(invitation) == LinkedInInvitation, 'LinkedInInvitation required'
url = '%s/~/mailbox' % ENDPOINTS.PEOPLE
try:
response = self.make_request('POST', url,
data=json.dumps(invitation.json))
response.raise_for_status()
except (requests.ConnectionError, requests.HTTPError), error:
raise LinkedInHTTPError(error.message)
return True
3
Example 34
Project: daruma Source File: TestServerProvider.py
@contextmanager
def exception_handler(self):
try:
yield
except requests.ConnectionError:
raise exceptions.ConnectionFailure(self)
except:
raise exceptions.ProviderOperationFailure(self)
3
Example 35
def connect(self):
try:
kw = {'ssl_ctx': SSL.Context(SSL.SSLv23_METHOD)}
self.sock = SocketLike(self.host, self.port, **kw)
except DNSResolutionError:
raise requests.ConnectionError
3
Example 36
Project: python-lib Source File: keenio_tests.py
@mock.patch('keen.count', return_value=0)
def test_has_build_id_mock(self, keen_count_func):
"""Test keenio.has_build_id() with a mocked keen.count"""
# test with some token (value doesn't matter, keen.count is mocked)
keen.project_id = "1234abcd"
keen.read_key = "4567abcd5678efgh"
# should return false if ID doesn't exist
self.assertFalse(keenio.has_build_id("test", 123))
# should return true if does exist
keen_count_func.return_value = 1
self.assertTrue(keenio.has_build_id("test", 123))
# test raising ConnectionError
keen_count_func.side_effect = requests.ConnectionError
self.assertRaises(SystemError, keenio.has_build_id, "test", 123)
3
Example 37
Project: Brownian Source File: ajax.py
@dajaxice_register
def updateIndices(request):
try:
indices = utils.es.getIndices()
except requests.ConnectionError:
raise requests.ConnectionError("Error - could not connect to ElasticSearch server to fetch indices.")
request.session['indices'] = indices
return True
3
Example 38
Project: wercker-cli Source File: test_metrics.py
def test_track_application_startup_fails_silently_on_ConnectionError(self):
err = requests.ConnectionError()
the_method = mock.Mock(side_effect=err)
with mock.patch(track_command_usage_path, the_method) as puts:
try:
track_application_startup()
except requests.ConnectionError:
self.fail("track_application_startup didn't fail silently")
3
Example 39
Project: Mechanic Source File: update.py
@classmethod
def _fetch_updates(cls):
logger.info("Fetching updates...")
try:
updates = [e for e in Extension.all() if e.should_update]
except requests.ConnectionError:
raise Update.ConnectionError
cls._set_cached(updates)
Storage.set('last_checked_at', time.time())
return updates
3
Example 40
Project: SmokeDetector Source File: excepthook.py
def uncaught_exception(exctype, value, tb):
now = datetime.utcnow()
delta = now - UtcDate.startup_utc_date
seconds = delta.total_seconds()
tr = '\n'.join((traceback.format_tb(tb)))
exception_only = ''.join(traceback.format_exception_only(exctype, value)).strip()
logged_msg = "{exception}\n{now} UTC\n{row}\n\n".format(exception=exception_only, now=now, row=tr)
print(logged_msg)
with open("errorLogs.txt", "a") as f:
f.write(logged_msg)
if seconds < 180 and exctype != WebSocketConnectionClosedException\
and exctype != KeyboardInterrupt and exctype != SystemExit and exctype != requests.ConnectionError:
os._exit(4)
else:
os._exit(1)
3
Example 41
Project: integration_tests Source File: api.py
def _sending_request(self, func, retries=2):
while retries:
try:
return func()
except requests.ConnectionError as e:
last_connection_exception = e
retries -= 1
raise last_connection_exception
3
Example 42
Project: ripe-atlas-tools Source File: probe_search.py
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()
3
Example 43
Project: rtv Source File: test_objects.py
@pytest.mark.parametrize('use_ascii', [True, False])
def test_objects_load_screen_exception_handled(terminal, stdscr, use_ascii):
terminal.config['ascii'] = use_ascii
# Raising a handled exception should get stored on the loaders
with terminal.loader(delay=0):
assert terminal.loader._animator.is_alive()
raise requests.ConnectionError()
assert not terminal.loader._is_running
assert not terminal.loader._animator.is_alive()
assert isinstance(terminal.loader.exception, requests.ConnectionError)
error_message = 'ConnectionError'.encode('ascii' if use_ascii else 'utf-8')
stdscr.subwin.addstr.assert_called_with(1, 1, error_message)
3
Example 44
Project: gae-boilerplate Source File: linkedin.py
def search_profile(self, selectors=None, params=None, headers=None):
if selectors:
url = '%s:(%s)' % (ENDPOINTS.PEOPLE_SEARCH,
LinkedInSelector.parse(selectors))
else:
url = ENDPOINTS.PEOPLE_SEARCH
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 45
Project: gae-boilerplate Source File: linkedin.py
def get_company_products(self, company_id, selectors=None, params=None,
headers=None):
url = '%s/%s/products' % (ENDPOINTS.COMPANIES, str(company_id))
if selectors:
url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors))
try:
response = self.make_request('GET', url, params=params, headers=headers)
response = response.json()
except requests.ConnectionError as error:
raise LinkedInHTTPError(error.message)
else:
if not self.request_succeeded(response):
raise LinkedInError(response)
return response
3
Example 46
def _manage_resource(self, resource_type):
"""
Routine for a worker thread. Syncs with API for the given resource
and starts a watch. If an error occurs within the watch, will re-sync
with the API and re-start the watch.
"""
while True:
try:
# Sync existing resources for this type.
resource_version = self._sync_resources(resource_type)
# Start a watch from the latest resource_version.
self._watch_resource(resource_type, resource_version)
except requests.ConnectionError, requests.ChunkedEncodingError:
_log.exception("Connection error querying: %s", resource_type)
except requests.HTTPError:
_log.exception("HTTP error querying: %s", resource_type)
3
Example 47
Project: HTPC-Manager Source File: utorrent.py
def fetch(self, args):
"""
:param args:
:rtype: requests.Response
:return:
"""
password = htpc.settings.get('utorrent_password', '')
username = htpc.settings.get('utorrent_username', '')
host = htpc.settings.get('utorrent_host')
port = htpc.settings.get('utorrent_port')
try:
return self._fetch(host, port, username, password, args)
except requests.ConnectionError:
raise ConnectionError
3
Example 48
def report_err(self, imgid):
self.data['imgid'] = imgid
if self.data['imgdata']:
del self.data['imgdata']
try:
r = self.s.post('http://apib.sz789.net:88/ReportError.ashx', self.data)
return r.json()
except requests.ConnectionError:
return self.report_err(imgid)
except:
return False
3
Example 49
Project: ClusterRunner Source File: cluster_slave.py
def _is_master_responsive(self):
"""
Ping the master to check if it is still alive. Code using this method should treat the return value as a
*probable* truth since the state of the master can change at any time. This method is not a replacement for
error handling.
:return: Whether the master is responsive or not
:rtype: bool
"""
# todo: This method repeats some logic we have in the deployment code (checking a service). We should DRY it up.
is_responsive = True
try:
self._network.get(self._master_api.url())
except requests.ConnectionError:
is_responsive = False
return is_responsive
3
Example 50
Project: gae-boilerplate Source File: linkedin.py
def follow_company(self, company_id):
url = '%s/~/following/companies' % ENDPOINTS.PEOPLE
post = {'id': company_id}
try:
response = self.make_request('POST', url, data=json.dumps(post))
response.raise_for_status()
except (requests.ConnectionError, requests.HTTPError), error:
raise LinkedInHTTPError(error.message)
else:
return True