cli: cleanup http error handling

Use more specific exception request exception handling to provide
better error messages.

Define an interal request function for get, post and delete to
reuse code.
master v0.3.3-15
Alejandro Sirgo Rica 2024-12-16 11:40:34 +01:00
parent 2f870d7b6a
commit 7d2678422e
1 changed files with 23 additions and 34 deletions

View File

@ -46,53 +46,42 @@ def _log_http_status_code(res):
class OgREST():
def __init__(self, ip, port, api_token):
if not ip or not port or not api_token:
raise ValueError("IP, port, and API token must be provided.")
self.URL = f'http://{ip}:{port}'
self.HEADERS = {'Authorization': api_token}
def get(self, path, payload=None):
def _request(self, method, path, payload, expected_status):
try:
res = requests.get(f'{self.URL}{path}',
headers=self.HEADERS,
json=payload)
if res.status_code != 200:
res = requests.request(
method,
f'{self.URL}{path}',
headers=self.HEADERS,
json=payload,
)
if res.status_code not in expected_status:
_log_http_status_code(res)
return None
return res
except requests.exceptions.ConnectionError:
print("Cannot connect to ogserver")
except requests.exceptions.Timeout:
print("Request to ogserver timed out")
except requests.exceptions.TooManyRedirects:
print("Too many redirects occurred while contacting ogserver")
except requests.exceptions.RequestException as e:
print(f"Error: Cannot connect to ogServer: {e}")
return None
print(f"An error occurred while contacting ogserver: {e}")
return None
return res
def get(self, path, payload, payload=None):
return self._request('GET', path, payload, expected_status={200})
def post(self, path, payload):
try:
res = requests.post(f'{self.URL}{path}',
headers=self.HEADERS,
json=payload)
if res.status_code not in {200, 202}:
_log_http_status_code(res)
return None
except requests.exceptions.RequestException as e:
print(f"Error: Cannot connect to ogServer: {e}")
return None
return res
return self._request('POST', path, payload, expected_status={200, 202})
def delete(self, path, payload):
try:
res = requests.delete(f'{self.URL}{path}',
headers=self.HEADERS,
json=payload)
if res.status_code != 200:
_log_http_status_code(res)
return None
except IOError as e:
print(f"Error: Cannot connect to ogServer: {e}")
return None
return res
return self._request('DELETE', path, payload, expected_status={200})
class OgCLI():