diff --git a/swh/core/api/__init__.py b/swh/core/api/__init__.py --- a/swh/core/api/__init__.py +++ b/swh/core/api/__init__.py @@ -178,12 +178,9 @@ post_data.pop("cur", None) post_data.pop("db", None) + data = post_data or {} # Send the request. - if http_method == "POST": - return self.post(meth._endpoint_path, post_data) - else: - data = post_data or {} - return self.get(meth._endpoint_path, data=data) + return self.post_or_get(http_method, meth._endpoint_path, data) if meth_name not in attributes: attributes[meth_name] = meth_ @@ -256,28 +253,10 @@ if self.timeout and "timeout" not in opts: opts["timeout"] = self.timeout try: - return getattr(self.session, verb)(self._url(endpoint), **opts) + return getattr(self.session, verb.lower())(self._url(endpoint), **opts) except requests.exceptions.ConnectionError as e: raise self.api_exception(e) - def post(self, endpoint, data, **opts): - chunk_size = opts.pop("chunk_size", self.chunk_size) - response = self.raw_verb( - "post", - endpoint, - data=self._encode_data(data), - headers={ - "content-type": "application/x-msgpack", - "accept": "application/x-msgpack", - }, - **opts, - ) - if opts.get("stream") or response.headers.get("transfer-encoding") == "chunked": - self.raise_for_status(response) - return response.iter_content(chunk_size) - else: - return self._decode_response(response) - def _encode_data(self, data): if isinstance(data, (abc.Iterator, abc.Generator)): data = ( @@ -287,13 +266,13 @@ data = encode_data(data, extra_encoders=self.extra_type_encoders) return data - post_stream = post - - def get(self, endpoint: str, data={}, **opts): + def post_or_get( + self, method: str, endpoint: str, data: Dict[str, Any] = {}, **opts + ): chunk_size = opts.pop("chunk_size", self.chunk_size) if data: response = self.raw_verb( - "get", + method, endpoint, headers={ "accept": "application/x-msgpack", @@ -304,7 +283,7 @@ ) else: response = self.raw_verb( - "get", endpoint, headers={"accept": "application/x-msgpack"}, **opts + method, endpoint, headers={"accept": "application/x-msgpack"}, **opts ) if opts.get("stream") or response.headers.get("transfer-encoding") == "chunked": @@ -313,8 +292,10 @@ else: return self._decode_response(response) + post_stream = post_or_get + def get_stream(self, endpoint, **opts): - return self.get(endpoint, stream=True, **opts) + return self.post_or_get("get", endpoint, stream=True, **opts) def raise_for_status(self, response) -> None: """check response HTTP status code and raise an exception if it denotes an