本文整理汇总了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)
示例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
示例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
示例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
示例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
示例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
示例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()
示例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
示例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
)
示例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']
示例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
示例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
示例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 == {}
示例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))