Skip to content

Commit

Permalink
kernelci.api: rework and enhance the api _post() method
Browse files Browse the repository at this point in the history
Simplify the base case, document the method and make it capable of
handling both string and dict payloads (automatically detected).

The default and most frequent use case will still be to pass a dict to
it, which will be sent to the server as a json object or as an encoded
string, depending on the <json_data> parameter.

The additional capability of accepting a string fits the use cases where
we might have an already processed json definition to POST instead of a
python dict.

Signed-off-by: Ricardo Cañuelo <[email protected]>
  • Loading branch information
Ricardo Cañuelo authored and nuclearcat committed Feb 22, 2024
1 parent 5d916a5 commit 6e8d6c5
Showing 1 changed file with 40 additions and 10 deletions.
50 changes: 40 additions & 10 deletions kernelci/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,21 +71,51 @@ def _get(self, path, params=None):
return resp

def _post(self, path, data=None, params=None, json_data=True):
"""Issues an API POST request to the endpoint specified in <path>.
Arguments:
path: API endpoint
data: request payload. It can be passed as a dict by default
or as a string, which is assumed to be
x-www-form-urlencoded
params: additional parameters that will be passed to the
requests <post> call
json_data: True if the payload is a json definition, False for
any other type of payload
"""
url = self.make_url(path)
if json_data:
jdata = json.dumps(data)
resp = requests.post(
url, jdata, headers=self.data.headers,
params=params, timeout=self.data.timeout
)
else:
headers = self.data.headers.copy()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
if isinstance(data, str):
# If the payload is a string we pass it as it is to
# requests.post, but in this case we have to explicitly
# specify the Content-Type header
if json_data:
headers = self.data.headers | {
'Content-Type': 'application/json'
}
else:
headers = self.data.headers | {
'Content-Type': 'application/x-www-form-urlencoded'
}
resp = requests.post(
url, data, headers=headers,
params=params, timeout=self.data.timeout
)
resp.raise_for_status()
else:
# When passing a dict to requests.post, it will
# automatically encode it as a string if necessary and set
# the Content-Type header
if json_data:
resp = requests.post(
url, json=data, headers=self.data.headers,
params=params, timeout=self.data.timeout
)
else:
resp = requests.post(
url, data, headers=self.data.headers,
params=params, timeout=self.data.timeout
)
resp.raise_for_status()
return resp

def _put(self, path, data=None, params=None):
Expand Down

0 comments on commit 6e8d6c5

Please sign in to comment.