def request(self, *args, **kwargs): """ Formats the request into a dict representing the headers and body that will be used to make the API call. """ kwargs.setdefault("headers", kwargs.get("headers", {})) kwargs["headers"]["User-Agent"] = self.user_agent kwargs["headers"]["Accept"] = "application/json" if "body" in kwargs: kwargs["headers"]["Content-Type"] = "application/json" kwargs["body"] = json.dumps(kwargs["body"]) self.http_log_req(args, kwargs) resp, body = super(BaseClient, self).request(*args, **kwargs) self.http_log_resp(resp, body) if body: try: body = json.loads(body) except ValueError: pass else: body = None if resp.status >= 400: raise exc.from_response(resp, body) return resp, body
def request(method, uri, *args, **kwargs): """ Handles all the common functionality required for API calls. Returns the resulting response object. Formats the request into a dict representing the headers and body that will be used to make the API call. """ req_method = req_methods[method.upper()] raise_exception = kwargs.pop("raise_exception", True) kwargs["headers"] = kwargs.get("headers", {}) http_log_req(method, uri, args, kwargs) data = None if "data" in kwargs: # The 'data' kwarg is used when you don't want json encoding. data = kwargs.pop("data") elif "body" in kwargs: if "Content-Type" not in kwargs["headers"]: kwargs["headers"]["Content-Type"] = "application/json" data = json.dumps(kwargs.pop("body")) if data: resp = req_method(uri, data=data, **kwargs) else: resp = req_method(uri, **kwargs) try: body = resp.json() except ValueError: # No JSON in response body = resp.content http_log_resp(resp, body) if resp.status_code >= 400 and raise_exception: raise exc.from_response(resp, body) return resp, body
def _extract_service_catalog(self, uri, resp, body, extract_token=True): """ See what the auth service told us and process the response. We may get redirected to another site, fail, or actually get back a service catalog with a token and our endpoints. """ if resp.status == 200: # content must always present try: self.auth_url = uri self.service_catalog = service_catalog.ServiceCatalog(body) if extract_token: self.auth_token = self.service_catalog.get_token() management_url = self.service_catalog.url_for( attr="region", filter_value=self.region_name, endpoint_type=self.endpoint_type, service_type=self.service_type, service_name=self.service_name) self.management_url = management_url.rstrip("/") return None except exc.AmbiguousEndpoints: print "Found more than one valid endpoint. Use a more restrictive filter" raise except KeyError: raise exc.AuthorizationFailure() except exc.EndpointNotFound: print "Could not find any suitable endpoint. Correct region?" raise elif resp.status == 305: return resp["location"] else: raise exc.from_response(resp, body)
def _v1_auth(self, uri): """ The original auth system for OpenStack. Probably not used anymore. """ if self.proxy_token: raise exc.NoTokenLookupException() headers = {"X-Auth-User": self.user, "X-Auth-Key": self.password} if self.tenant_id: headers["X-Auth-Project-Id"] = self.tenant_id resp, body = self._time_request(uri, "GET", headers=headers) if resp.status in (200, 204): # in some cases we get No Content try: mgmt_header = "x-server-management-url" self.management_url = resp[mgmt_header].rstrip("/") self.auth_token = resp["x-auth-token"] self.auth_url = uri except KeyError: raise exc.AuthorizationFailure() elif resp.status == 305: return resp["location"] else: raise exc.from_response(resp, body)
def test_from_response_with_body(self): fake_resp = fakes.FakeResponse() fake_resp.status_code = 666 fake_body = {"error": {"message": "fake_message", "details": "fake_details"}} ret = exc.from_response(fake_resp, fake_body) self.assertTrue(isinstance(ret, exc.ClientException)) self.assertEqual(ret.code, fake_resp.status_code) self.assertEqual(ret.message, "fake_message") self.assertEqual(ret.details, "fake_details") self.assertTrue("HTTP 666" in str(ret))
def test_from_response_with_body(self): fake_resp = fakes.FakeResponse() fake_resp.status = 666 fake_body = {"error": { "message": "fake_message", "details": "fake_details"}} ret = exc.from_response(fake_resp, fake_body) self.assertTrue(isinstance(ret, exc.ClientException)) self.assertEqual(ret.code, fake_resp.status) self.assertEqual(ret.message, "fake_message") self.assertEqual(ret.details, "fake_details") self.assertTrue("HTTP 666" in str(ret))
def request(self, uri, method, *args, **kwargs): """ Formats the request into a dict representing the headers and body that will be used to make the API call. """ if self.timeout: kwargs["timeout"] = self.timeout kwargs["verify"] = self.verify_ssl kwargs.setdefault("headers", kwargs.get("headers", {})) kwargs["headers"]["User-Agent"] = self.user_agent kwargs["headers"]["Accept"] = "application/json" # Allow subclasses to add their own headers self._add_custom_headers(kwargs["headers"]) resp, body = pyrax.http.request(method, uri, *args, **kwargs) if resp.status_code >= 400: raise exc.from_response(resp, body) return resp, body
def request(self, uri, method, *args, **kwargs): """ Formats the request into a dict representing the headers and body that will be used to make the API call. """ if self.timeout: kwargs["timeout"] = self.timeout kwargs["verify"] = self.verify_ssl kwargs.setdefault("headers", kwargs.get("headers", {})) kwargs["headers"]["User-Agent"] = self.user_agent kwargs["headers"]["Accept"] = "application/json" if "body" in kwargs: if "Content-Type" not in kwargs["headers"]: kwargs["headers"]["Content-Type"] = "application/json" # JSON-encode by default, unless explicitly told not to. use_json = kwargs.pop("json_encode", True) if use_json: kwargs["body"] = json.dumps(kwargs["body"]) # Allow subclasses to add their own headers self._add_custom_headers(kwargs["headers"]) resp, body = pyrax.http.request(method, uri, *args, **kwargs) if resp.status_code >= 400: raise exc.from_response(resp, body) return resp, body
def test_from_response_no_body(self): fake_resp = fakes.FakeResponse() fake_resp.status = 666 ret = exc.from_response(fake_resp, None) self.assertTrue(isinstance(ret, exc.ClientException)) self.assertEqual(ret.code, fake_resp.status)