fix: handle empty response body in api_request
This commit is contained in:
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
__pycache__/
|
||||
@@ -46,11 +46,20 @@ def api_request(url, user, password, method="GET", data=None):
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=30) as resp:
|
||||
if resp.status == 204 or resp.status == 202:
|
||||
return {"status": resp.status}
|
||||
# Handle responses with no body
|
||||
if resp.status in (200, 201, 202, 204):
|
||||
body = resp.read().decode().strip()
|
||||
if not body:
|
||||
return {"status": resp.status}
|
||||
return json.loads(body)
|
||||
return json.loads(resp.read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": e.code, "message": e.read().decode()}
|
||||
body = e.read().decode()
|
||||
try:
|
||||
err_json = json.loads(body)
|
||||
return {"error": e.code, "message": err_json.get("errors", [{}])[0].get("message", body)}
|
||||
except json.JSONDecodeError:
|
||||
return {"error": e.code, "message": body}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user