From fd7ecbe2f77a1965cdfff362f2b121d2c269feb3 Mon Sep 17 00:00:00 2001 From: Nao Pross Date: Mon, 19 Oct 2020 09:10:24 +0200 Subject: Cleaner requests error and exception handling --- moodle.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'moodle.py') diff --git a/moodle.py b/moodle.py index ee60dc9..5d0f9bd 100644 --- a/moodle.py +++ b/moodle.py @@ -20,7 +20,16 @@ def api_call(url, token, function, **kwargs): data[str(k)] = v log.debug(f"calling api with POST to {api_url} with DATA {data}") - return requests.post(api_url, data=data) + try: + req = requests.post(api_url, data=data) + req.raise_for_status() + return req + except requests.HTTPError: + log.warn(f"Error code returned by HTTP(s) request") + return req + except (requests.ConnectionError, requests.Timeout, requests.ReadTimeout) as e: + log.error(f"Failed to connect for POST request:\n{str(e)}") + return None class RestApi: def __init__(self, instance_url, token): @@ -35,7 +44,11 @@ class ApiHelper: self.api = api def get_userid(self): - return self.api.core_webservice_get_site_info().json()["userid"] + req = self.api.core_webservice_get_site_info() + if req: + return req.json()["userid"] + else: + return None def get_file(self, url, local_path): with requests.post(url, data={"token": self.api._token}, stream=True) as r: -- cgit v1.2.1