summaryrefslogtreecommitdiffstats
path: root/cli/cli.py
diff options
context:
space:
mode:
authorAlejandro Sirgo Rica <asirgo@soleta.eu>2024-12-16 11:40:34 +0100
committerAlejandro Sirgo Rica <asirgo@soleta.eu>2024-12-16 12:49:46 +0100
commit7d2678422eb26f0930932fd8814c68eae0ea3dda (patch)
treea23c6c40e8815b528778f0d7866fd78d76e3d4cc /cli/cli.py
parent2f870d7b6a1e823530c5219504929c58b5f32b1d (diff)
cli: cleanup http error handlingv0.3.3-15
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.
Diffstat (limited to 'cli/cli.py')
-rw-r--r--cli/cli.py59
1 files changed, 24 insertions, 35 deletions
diff --git a/cli/cli.py b/cli/cli.py
index 8dce3f5..0aaf885 100644
--- a/cli/cli.py
+++ b/cli/cli.py
@@ -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():