def request(self, url, method, **kwargs): kwargs.setdefault('headers', kwargs.get('headers', {})) 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
def test_from_response_with_status_code_404(self): json_data = {"faultstring": "fake message", "debuginfo": "fake details"} method = 'GET' status_code = 404 url = 'http://example.com:9777/v1/assemblies/fake-id' ex = exc.from_response( FakeResponse(status_code=status_code, headers={"Content-Type": "application/json"}, json_data=json_data), method, url ) self.assertIsInstance(ex, exceptions.HttpError) self.assertEqual(json_data["faultstring"], ex.message) self.assertEqual(json_data["debuginfo"], ex.details) self.assertEqual(method, ex.method) self.assertEqual(url, ex.url) self.assertEqual(status_code, ex.http_status)
def request(self, method, url, **kwargs): """Send an http request with the specified characteristics. Wrapper around `requests.Session.request` to handle tasks such as setting headers, JSON encoding/decoding, and error handling. :param method: method of HTTP request :param url: URL of HTTP request :param kwargs: any other parameter that can be passed to ' requests.Session.request (such as `headers`) or `json` that will be encoded as JSON and used as `data` argument """ kwargs.setdefault("headers", kwargs.get("headers", {})) kwargs["headers"]["User-Agent"] = self.user_agent if self.original_ip: kwargs["headers"]["Forwarded"] = "for=%s;by=%s" % ( self.original_ip, self.user_agent) if self.timeout is not None: kwargs.setdefault("timeout", self.timeout) kwargs.setdefault("verify", self.verify) if self.cert is not None: kwargs.setdefault("cert", self.cert) self.serialize(kwargs) self._http_log_req(method, url, kwargs) if self.timings: start_time = time.time() resp = self.http.request(method, url, **kwargs) if self.timings: self.times.append(("%s %s" % (method, url), start_time, time.time())) self._http_log_resp(resp) if resp.status_code >= 400: _logger.debug( "Request returned failure status: %s", resp.status_code) raise exc.from_response(resp, method, url) return resp