diff options
author | Nao Pross <np@0hm.ch> | 2020-10-19 09:10:24 +0200 |
---|---|---|
committer | Nao Pross <np@0hm.ch> | 2020-10-19 09:10:24 +0200 |
commit | fd7ecbe2f77a1965cdfff362f2b121d2c269feb3 (patch) | |
tree | a2c1f7230c74f15d1812c022827d0a3116705745 | |
parent | Fix GUI log handler crash (diff) | |
download | Muddle-fd7ecbe2f77a1965cdfff362f2b121d2c269feb3.tar.gz Muddle-fd7ecbe2f77a1965cdfff362f2b121d2c269feb3.zip |
Cleaner requests error and exception handling
Diffstat (limited to '')
-rw-r--r-- | gui.py | 27 | ||||
-rw-r--r-- | moodle.py | 17 |
2 files changed, 27 insertions, 17 deletions
@@ -97,27 +97,24 @@ class MoodleFetcher(QThread): self.loadedItem.emit(MoodleItem.Type.CONTENT, content) def getCourses(self): - courses = self.api.core_enrol_get_users_courses(userid = self.apihelper.get_userid()).json() - if "exception" in courses: - log.error("failed to load courses") - log.debug(courses) + coursesReq = self.api.core_enrol_get_users_courses(userid = self.apihelper.get_userid()) + if not coursesReq: return [] - else: - return courses + + return coursesReq.json() def getSections(self, course): if not "id" in course: - log.error("cannot get sections from invalid course") + log.error("cannot get sections from invalid course (no id)") log.debug(course) return [] - else: - sections = self.api.core_course_get_contents(courseid = str(course["id"])).json() - if "exception" in sections: - log.error(f"failed to load sections from course with id {course['id']} ({course['shortname']})") - log.debug(sections) - return [] - else: - return sections + + sectionsReq = self.api.core_course_get_contents(courseid = str(course["id"])) + if not sectionsReq: + return + + sections = sectionsReq.json() + return sections def getModules(self, section): if "modules" in section: @@ -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: |