Here are the examples of the python api requests.exceptions.SSLError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
60 Examples
0
Example 51
def _send(self, host, method='GET', **kwargs):
url = None
params = kwargs['params'] if 'params' in kwargs else {}
if 'wt' not in params:
params['wt'] = 'json'
params['indent'] = False
for field in params:
if type(params[field]) is bool:
params[field] = str(params[field]).lower()
if not host.endswith('/'):
host += '/'
data = kwargs['data'] if 'data' in kwargs else {}
if 'endpoint' in kwargs:
if 'collection' in kwargs:
url = "{}{}/{}".format(host,kwargs['collection'], kwargs['endpoint'])
else:
url = host + kwargs['endpoint']
else:
raise ValueError("No URL 'endpoint' set in parameters to send_request")
self.logger.debug("Sending Request to {} with {}".format(url,", ".join([str("{}={}".format(key, params[key])) for key in params])))
#Some code used from ES python client.
start = time.time()
try:
res = self.session.request(method, url, params=params, data=data,headers = {'content-type': 'application/json'})
duration = time.time() - start
self.logger.debug("Request Completed in {} Seconds".format(round(duration,2)))
except requests.exceptions.SSLError as e:
self._log_connection_error(method, url, body, time.time() - start, exception=e)
raise ConnectionError('N/A', str(e), e)
except requests.Timeout as e:
self._log_connection_error(method, url, body, time.time() - start, exception=e)
raise ConnectionError('TIMEOUT', str(e), e)
except requests.ConnectionError as e:
self._log_connection_error(method, url, str(e), time.time() - start, exception=e)
raise ConnectionError('N/A', str(e), e)
if (200 <= res.status_code < 300):
return [res.json(), {'url': res.url}]
else:
if res.status_code == 404:
raise ConnectionError("404 - {}".format(res.url))
elif res.status_code == 401:
raise ConnectionError("401 - {}".format(res.url))
elif res.status_code == 500:
raise SolrError("500 - " + res.url + " "+res.text)
else:
raise SolrError(res.url+" "+res.text)
0
Example 52
Project: cinder Source File: authentication.py
def authenticate_user(self, username, password):
"""Makes REST API call to generate the authentication token.
Authentication token is generated for the specified user after
validation
:param username: Name of the user
:param password: Password for the user
:returns: The authtoken
"""
SEC_REDIRECT = 302
SEC_AUTHTOKEN_HEADER = 'X-SDS-AUTH-TOKEN'
LB_API_PORT = 4443
# Port on which load-balancer/reverse-proxy listens to all incoming
# requests for CoprHD REST APIs
APISVC_PORT = 8443 # Port on which apisvc listens to incoming requests
cookiejar = cookie_lib.LWPCookieJar()
url = ('https://%(ip)s:%(port)d%(uri)s' %
{'ip': self.ipaddr, 'port': self.port,
'uri': self.URI_AUTHENTICATION})
try:
if self.port == APISVC_PORT:
login_response = requests.get(
url, headers=self.HEADERS, verify=False,
auth=(username, password), cookies=cookiejar,
allow_redirects=False, timeout=common.TIMEOUT_SEC)
if login_response.status_code == SEC_REDIRECT:
location = login_response.headers['Location']
if not location:
raise common.CoprHdError(
common.CoprHdError.HTTP_ERR, (_("The redirect"
" location of the"
" authentication"
" service is not"
" provided")))
# Make the second request
login_response = requests.get(
location, headers=self.HEADERS, verify=False,
cookies=cookiejar, allow_redirects=False,
timeout=common.TIMEOUT_SEC)
if (login_response.status_code !=
requests.codes['unauthorized']):
raise common.CoprHdError(
common.CoprHdError.HTTP_ERR, (_("The"
" authentication"
" service failed"
" to reply with"
" 401")))
# Now provide the credentials
login_response = requests.get(
location, headers=self.HEADERS,
auth=(username, password), verify=False,
cookies=cookiejar, allow_redirects=False,
timeout=common.TIMEOUT_SEC)
if login_response.status_code != SEC_REDIRECT:
raise common.CoprHdError(
common.CoprHdError.HTTP_ERR,
(_("Access forbidden: Authentication required")))
location = login_response.headers['Location']
if not location:
raise common.CoprHdError(
common.CoprHdError.HTTP_ERR,
(_("The"
" authentication service failed to provide the"
" location of the service URI when redirecting"
" back")))
authtoken = login_response.headers[SEC_AUTHTOKEN_HEADER]
if not authtoken:
details_str = self.extract_error_detail(login_response)
raise common.CoprHdError(common.CoprHdError.HTTP_ERR,
(_("The token is not"
" generated by"
" authentication service."
"%s") %
details_str))
# Make the final call to get the page with the token
new_headers = self.HEADERS
new_headers[SEC_AUTHTOKEN_HEADER] = authtoken
login_response = requests.get(
location, headers=new_headers, verify=False,
cookies=cookiejar, allow_redirects=False,
timeout=common.TIMEOUT_SEC)
if login_response.status_code != requests.codes['ok']:
raise common.CoprHdError(
common.CoprHdError.HTTP_ERR, (_(
"Login failure code: "
"%(statuscode)s Error: %(responsetext)s") %
{'statuscode': six.text_type(
login_response.status_code),
'responsetext': login_response.text}))
elif self.port == LB_API_PORT:
login_response = requests.get(
url, headers=self.HEADERS, verify=False,
cookies=cookiejar, allow_redirects=False)
if(login_response.status_code ==
requests.codes['unauthorized']):
# Now provide the credentials
login_response = requests.get(
url, headers=self.HEADERS, auth=(username, password),
verify=False, cookies=cookiejar, allow_redirects=False)
authtoken = None
if SEC_AUTHTOKEN_HEADER in login_response.headers:
authtoken = login_response.headers[SEC_AUTHTOKEN_HEADER]
else:
raise common.CoprHdError(
common.CoprHdError.HTTP_ERR,
(_("Incorrect port number. Load balanced port is: "
"%(lb_api_port)s, api service port is: "
"%(apisvc_port)s") %
{'lb_api_port': LB_API_PORT,
'apisvc_port': APISVC_PORT}))
if not authtoken:
details_str = self.extract_error_detail(login_response)
raise common.CoprHdError(
common.CoprHdError.HTTP_ERR,
(_("The token is not generated by authentication service."
" %s") % details_str))
if login_response.status_code != requests.codes['ok']:
error_msg = None
if login_response.status_code == 401:
error_msg = _("Access forbidden: Authentication required")
elif login_response.status_code == 403:
error_msg = _("Access forbidden: You don't have"
" sufficient privileges to perform"
" this operation")
elif login_response.status_code == 500:
error_msg = _("Bourne internal server error")
elif login_response.status_code == 404:
error_msg = _(
"Requested resource is currently unavailable")
elif login_response.status_code == 405:
error_msg = (_("GET method is not supported by resource:"
" %s"),
url)
elif login_response.status_code == 503:
error_msg = _("Service temporarily unavailable:"
" The server is temporarily unable"
" to service your request")
else:
error_msg = login_response.text
raise common.CoprHdError(common.CoprHdError.HTTP_ERR,
(_("HTTP code: %(status_code)s"
", response: %(reason)s"
" [%(error_msg)s]") % {
'status_code': six.text_type(
login_response.status_code),
'reason': six.text_type(
login_response.reason),
'error_msg': six.text_type(
error_msg)
}))
except (exceptions.SSLError, socket.error, exceptions.ConnectionError,
exceptions.Timeout) as e:
raise common.CoprHdError(
common.CoprHdError.HTTP_ERR, six.text_type(e))
return authtoken
0
Example 53
Project: cinder Source File: commoncoprhdapi.py
def service_json_request(ip_addr, port, http_method, uri, body,
contenttype='application/json', customheaders=None):
"""Used to make an HTTP request and get the response.
The message body is encoded in JSON format
:param ip_addr: IP address or host name of the server
:param port: port number of the server on which it
is listening to HTTP requests
:param http_method: one of GET, POST, PUT, DELETE
:param uri: the request URI
:param body: the request payload
:returns: a tuple of two elements: (response body, response headers)
:raises: CoprHdError in case of HTTP errors with err_code 3
"""
SEC_AUTHTOKEN_HEADER = 'X-SDS-AUTH-TOKEN'
headers = {'Content-Type': contenttype,
'ACCEPT': 'application/json, application/octet-stream',
'X-EMC-REST-CLIENT': 'TRUE'}
if customheaders:
headers.update(customheaders)
try:
protocol = "https://"
if port == 8080:
protocol = "http://"
url = protocol + ip_addr + ":" + six.text_type(port) + uri
cookiejar = cookie_lib.LWPCookieJar()
headers[SEC_AUTHTOKEN_HEADER] = AUTH_TOKEN
if http_method == 'GET':
response = requests.get(url, headers=headers, verify=False,
cookies=cookiejar)
elif http_method == 'POST':
response = requests.post(url, data=body, headers=headers,
verify=False, cookies=cookiejar)
elif http_method == 'PUT':
response = requests.put(url, data=body, headers=headers,
verify=False, cookies=cookiejar)
elif http_method == 'DELETE':
response = requests.delete(url, headers=headers, verify=False,
cookies=cookiejar)
else:
raise CoprHdError(CoprHdError.HTTP_ERR,
(_("Unknown/Unsupported HTTP method: %s") %
http_method))
if (response.status_code == requests.codes['ok'] or
response.status_code == 202):
return (response.text, response.headers)
error_msg = None
if response.status_code == 500:
response_text = json_decode(response.text)
error_details = ""
if 'details' in response_text:
error_details = response_text['details']
error_msg = (_("CoprHD internal server error. Error details: %s"),
error_details)
elif response.status_code == 401:
error_msg = _("Access forbidden: Authentication required")
elif response.status_code == 403:
error_msg = ""
error_details = ""
error_description = ""
response_text = json_decode(response.text)
if 'details' in response_text:
error_details = response_text['details']
error_msg = (_("%(error_msg)s Error details:"
" %(error_details)s"),
{'error_msg': error_msg,
'error_details': error_details
})
elif 'description' in response_text:
error_description = response_text['description']
error_msg = (_("%(error_msg)s Error description:"
" %(error_description)s"),
{'error_msg': error_msg,
'error_description': error_description
})
else:
error_msg = _("Access forbidden: You don't have"
" sufficient privileges to perform this"
" operation")
elif response.status_code == 404:
error_msg = "Requested resource not found"
elif response.status_code == 405:
error_msg = six.text_type(response.text)
elif response.status_code == 503:
error_msg = ""
error_details = ""
error_description = ""
response_text = json_decode(response.text)
if 'code' in response_text:
errorCode = response_text['code']
error_msg = "Error " + six.text_type(errorCode)
if 'details' in response_text:
error_details = response_text['details']
error_msg = error_msg + ": " + error_details
elif 'description' in response_text:
error_description = response_text['description']
error_msg = error_msg + ": " + error_description
else:
error_msg = _("Service temporarily unavailable:"
" The server is temporarily unable to"
" service your request")
else:
error_msg = response.text
if isinstance(error_msg, unicode):
error_msg = error_msg.encode('utf-8')
raise CoprHdError(CoprHdError.HTTP_ERR,
(_("HTTP code: %(status_code)s"
", %(reason)s"
" [%(error_msg)s]") % {
'status_code': six.text_type(
response.status_code),
'reason': six.text_type(
response.reason),
'error_msg': six.text_type(
error_msg)
}))
except (CoprHdError, socket.error, exceptions.SSLError,
exceptions.ConnectionError, exceptions.TooManyRedirects,
exceptions.Timeout) as e:
raise CoprHdError(CoprHdError.HTTP_ERR, six.text_type(e))
# TODO(Ravi) : Either following exception should have proper message or
# IOError should just be combined with the above statement
except IOError as e:
raise CoprHdError(CoprHdError.HTTP_ERR, six.text_type(e))
0
Example 54
Project: cloudbase-init Source File: test_base.py
def test_get_response_ssl_error(self):
ssl_error = requests.exceptions.SSLError()
self._test_get_data(expected_response=ssl_error,
expected_value=exception.CertificateVerifyFailed)
0
Example 55
def backup_blocks(self, backup):
"""
:param backup:
:type backup: freezer.storage.base.Backup
:return:
"""
split = backup.data_path.split('/', 1)
try:
chunks = self.client_manager.create_swift().get_object(
split[0], split[1],
resp_chunk_size=self.max_segment_size)[1]
except requests.exceptions.SSLError as e:
LOG.warning(e)
chunks = self.client_manager.create_swift().get_object(
split[0], split[1],
resp_chunk_size=self.max_segment_size)[1]
for chunk in chunks:
yield chunk
0
Example 56
def _send_request(self, url, method, redirect, log, logger,
connect_retries, connect_retry_delay=0.5, **kwargs):
# NOTE(jamielennox): We handle redirection manually because the
# requests lib follows some browser patterns where it will redirect
# POSTs as GETs for certain statuses which is not want we want for an
# API. See: https://en.wikipedia.org/wiki/Post/Redirect/Get
# NOTE(jamielennox): The interaction between retries and redirects are
# handled naively. We will attempt only a maximum number of retries and
# redirects rather than per request limits. Otherwise the extreme case
# could be redirects * retries requests. This will be sufficient in
# most cases and can be fixed properly if there's ever a need.
try:
try:
resp = self.session.request(method, url, **kwargs)
except requests.exceptions.SSLError as e:
msg = 'SSL exception connecting to %(url)s: %(error)s' % {
'url': url, 'error': e}
raise exceptions.SSLError(msg)
except requests.exceptions.Timeout:
msg = 'Request to %s timed out' % url
raise exceptions.ConnectTimeout(msg)
except requests.exceptions.ConnectionError as e:
# NOTE(sdague): urllib3/requests connection error is a
# translation of SocketError. However, SocketError
# happens for many different reasons, and that low
# level message is often really important in figuring
# out the difference between network misconfigurations
# and firewall blocking.
msg = 'Unable to establish connection to %s: %s' % (url, e)
raise exceptions.ConnectFailure(msg)
except requests.exceptions.RequestException as e:
msg = 'Unexpected exception for %(url)s: %(error)s' % {
'url': url, 'error': e}
raise exceptions.UnknownConnectionError(msg, e)
except exceptions.RetriableConnectionFailure as e:
if connect_retries <= 0:
raise
logger.info('Failure: %(e)s. Retrying in %(delay).1fs.',
{'e': e, 'delay': connect_retry_delay})
time.sleep(connect_retry_delay)
return self._send_request(
url, method, redirect, log, logger,
connect_retries=connect_retries - 1,
connect_retry_delay=connect_retry_delay * 2,
**kwargs)
if log:
self._http_log_response(response=resp, logger=logger)
if resp.status_code in self._REDIRECT_STATUSES:
# be careful here in python True == 1 and False == 0
if isinstance(redirect, bool):
redirect_allowed = redirect
else:
redirect -= 1
redirect_allowed = redirect >= 0
if not redirect_allowed:
return resp
try:
location = resp.headers['location']
except KeyError:
logger.warning("Failed to redirect request to %s as new "
"location was not provided.", resp.url)
else:
# NOTE(jamielennox): We don't pass through connect_retry_delay.
# This request actually worked so we can reset the delay count.
new_resp = self._send_request(
location, method, redirect, log, logger,
connect_retries=connect_retries,
**kwargs)
if not isinstance(new_resp.history, list):
new_resp.history = list(new_resp.history)
new_resp.history.insert(0, resp)
resp = new_resp
return resp
0
Example 57
def _send_request(self, url, method, redirect, log, logger,
connect_retries, connect_retry_delay=0.5, **kwargs):
# NOTE(jamielennox): We handle redirection manually because the
# requests lib follows some browser patterns where it will redirect
# POSTs as GETs for certain statuses which is not want we want for an
# API. See: https://en.wikipedia.org/wiki/Post/Redirect/Get
# NOTE(jamielennox): The interaction between retries and redirects are
# handled naively. We will attempt only a maximum number of retries and
# redirects rather than per request limits. Otherwise the extreme case
# could be redirects * retries requests. This will be sufficient in
# most cases and can be fixed properly if there's ever a need.
try:
try:
resp = self.session.request(method, url, **kwargs)
except requests.exceptions.SSLError as e:
msg = _('SSL exception connecting to %(url)s: '
'%(error)s') % {'url': url, 'error': e}
raise exceptions.SSLError(msg)
except requests.exceptions.Timeout:
msg = _('Request to %s timed out') % url
raise exceptions.RequestTimeout(msg)
except requests.exceptions.ConnectionError:
msg = _('Unable to establish connection to %s') % url
raise exceptions.ConnectionRefused(msg)
except (exceptions.RequestTimeout, exceptions.ConnectionRefused) as e:
if connect_retries <= 0:
raise
logger.info(_LI('Failure: %(e)s. Retrying in %(delay).1fs.'),
{'e': e, 'delay': connect_retry_delay})
time.sleep(connect_retry_delay)
return self._send_request(
url, method, redirect, log, logger,
connect_retries=connect_retries - 1,
connect_retry_delay=connect_retry_delay * 2,
**kwargs)
if log:
self._http_log_response(resp, logger)
if resp.status_code in self._REDIRECT_STATUSES:
# be careful here in python True == 1 and False == 0
if isinstance(redirect, bool):
redirect_allowed = redirect
else:
redirect -= 1
redirect_allowed = redirect >= 0
if not redirect_allowed:
return resp
try:
location = resp.headers['location']
except KeyError:
logger.warning(_LW("Failed to redirect request to %s as new "
"location was not provided."), resp.url)
else:
# NOTE(jamielennox): We don't pass through connect_retry_delay.
# This request actually worked so we can reset the delay count.
new_resp = self._send_request(
location, method, redirect, log, logger,
connect_retries=connect_retries,
**kwargs)
if not isinstance(new_resp.history, list):
new_resp.history = list(new_resp.history)
new_resp.history.insert(0, resp)
resp = new_resp
return resp
0
Example 58
Project: python-neutronclient Source File: client.py
def _cs_request(self, *args, **kwargs):
kargs = {}
kargs.setdefault('headers', kwargs.get('headers', {}))
kargs['headers']['User-Agent'] = USER_AGENT
if 'body' in kwargs:
kargs['body'] = kwargs['body']
if self.log_credentials:
log_kargs = kargs
else:
log_kargs = self._strip_credentials(kargs)
utils.http_log_req(_logger, args, log_kargs)
try:
resp, body = self.request(*args, **kargs)
except requests.exceptions.SSLError as e:
raise exceptions.SslCertificateValidationError(reason=e)
except Exception as e:
# Wrap the low-level connection error (socket timeout, redirect
# limit, decompression error, etc) into our custom high-level
# connection exception (it is excepted in the upper layers of code)
_logger.debug("throwing ConnectionFailed : %s", e)
raise exceptions.ConnectionFailed(reason=e)
utils.http_log_resp(_logger, resp, body)
if resp.status_code == 401:
raise exceptions.Unauthorized(message=body)
return resp, body
0
Example 59
Project: python-tackerclient Source File: client.py
def _cs_request(self, *args, **kwargs):
kargs = {}
kargs.setdefault('headers', kwargs.get('headers', {}))
kargs['headers']['User-Agent'] = self.USER_AGENT
if 'body' in kwargs:
kargs['body'] = kwargs['body']
if self.log_credentials:
log_kargs = kargs
else:
log_kargs = self._strip_credentials(kargs)
utils.http_log_req(_logger, args, log_kargs)
try:
resp, body = self.request(*args, **kargs)
except requests.exceptions.SSLError as e:
raise exceptions.SslCertificateValidationError(reason=e)
except Exception as e:
# Wrap the low-level connection error (socket timeout, redirect
# limit, decompression error, etc) into our custom high-level
# connection exception (it is excepted in the upper layers of code)
_logger.debug("throwing ConnectionFailed : %s", e)
raise exceptions.ConnectionFailed(reason=e)
utils.http_log_resp(_logger, resp, body)
if resp.status_code == 401:
raise exceptions.Unauthorized(message=body)
return resp, body
0
Example 60
Project: syntribos Source File: test_http_checks.py
def test_SSL_error(self):
signal = http_checks.check_fail(rex.SSLError())
self._assert_has_tags(self.conn_fail_tags, signal)
self._assert_has_slug("HTTP_FAIL_SSL_ERROR", signal)