Drop direct usage of simplejson

simplejson is not in requirements so is not install automatically.
The requests library uses the built-in json module instead of the 3rd-
party simplejson library in case the simplejson library is not present.
We should use the alias (requests.JsonDecodeError) instead of
the actual exception from underlying modules to adapt to that
selection logic.

Also remove duplicated code in __str__ and __repr__. The logic in
__repr__ does not contain handling for non-json response and looks
incomplete.

Change-Id: I89749eebc1e410f023169a115ffbfa9ef04cf3ad
This commit is contained in:
Takashi Kajinami 2024-05-03 22:23:04 +09:00
parent 1557000041
commit e64b943b77

View File

@ -15,7 +15,6 @@
import logging
import requests
import simplejson
LOG = logging.getLogger(__name__)
@ -32,7 +31,7 @@ class PrometheusAPIClientError(Exception):
decoded = self.resp.json()
if 'error' in decoded:
return f'[{self.resp.status_code}] {decoded["error"]}'
except simplejson.errors.JSONDecodeError:
except requests.JSONDecodeError:
# If an https endpoint is accessed as http,
# we get 400 status with plain text instead of
# json and decoding it raises exception.
@ -43,15 +42,7 @@ class PrometheusAPIClientError(Exception):
return f'[{decoded.status}]'
def __repr__(self) -> str:
if self.resp.status_code != requests.codes.ok:
if self.resp.status_code != 204:
decoded = self.resp.json()
if 'error' in decoded:
return f'[{self.resp.status_code}] {decoded["error"]}'
return f'[{self.resp.status_code}] {self.resp.reason}'
else:
decoded = self.resp.json()
return f'[{decoded.status}]'
return self.__str__()
class PrometheusMetric(object):