def _http_request(self, url, method, **kwargs): """Send an http request with the specified characteristics. Wrapper around httplib.HTTP(S)Connection.request to handle tasks such as setting headers and error handling. """ # Copy the kwargs so we can reuse the original in case of redirects kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {})) kwargs['headers'].setdefault('User-Agent', USER_AGENT) auth_token = self.auth_token() if auth_token: kwargs['headers'].setdefault('X-Auth-Token', auth_token) self.log_curl_request(method, url, kwargs) conn = self.get_connection() try: if self.proxy_url: conn_url = (self.endpoint.rstrip('/') + self._make_connection_url(url)) else: conn_url = self._make_connection_url(url) conn.request(method, conn_url, **kwargs) resp = conn.getresponse() except socket.gaierror as e: message = ("Error finding address for %(url)s: %(e)s" % dict(url=url, e=e)) raise exc.InvalidEndpoint(message=message) except (socket.error, socket.timeout) as e: endpoint = self.endpoint message = ("Error communicating with %(endpoint)s %(e)s" % dict(endpoint=endpoint, e=e)) raise exc.CommunicationError(message=message) body_iter = ResponseBodyIterator(resp) # Read body into string if it isn't obviously image data if resp.getheader('content-type', None) != 'application/octet-stream': body_str = ''.join([chunk for chunk in body_iter]) self.log_http_response(resp, body_str) body_iter = six.StringIO(body_str) else: self.log_http_response(resp) if 400 <= resp.status < 600: LOG.warn("Request returned failure status.") raise exc.from_response(resp, ''.join(body_iter)) elif resp.status in (301, 302, 305): # Redirected. Reissue the request to the new location. return self._http_request(resp['location'], method, **kwargs) elif resp.status == 300: raise exc.from_response(resp) return resp, body_iter
def test_from_response(self): class HTTPLibLikeResponse(object): status = 400 class RequestsLikeResponse(object): status_code = 401 class UnexpectedResponse(object): code = 200 self.assertEqual(HTTPLibLikeResponse.status, exc.from_response(HTTPLibLikeResponse).code) self.assertEqual(RequestsLikeResponse.status_code, exc.from_response(RequestsLikeResponse).code) self.assertRaises(TypeError, exc.from_response, UnexpectedResponse)
def request(self, url, method, **kwargs): kwargs.setdefault('headers', kwargs.get('headers', {})) # NOTE(sileht): The standard call raises errors from # keystoneauth, where we need to raise the ceilometerclient errors. raise_exc = kwargs.pop('raise_exc', True) with record_time(self.times, self.timings, method, url): resp, body = super(SessionClient, self).request(url, method, raise_exc=False, **kwargs) if raise_exc and resp.status_code >= 400: raise exc.from_response(resp, body) return resp