The task is to fetch some JSON data from an API with a GET request. If the location is not available for any reason, read a cache file. Otherwise write the cache file for future use.
The following function works but it is clumsy due to:
- The nested
except, which is difficult to read
- It's difficult to figure out what the error is (I am catching both
JSONDecodeErrorto avoid further nesting
- I don't dare to use a context manager for opening the file (
with) due to a further nesting level within a
Have you got any ideas for improvement?
def fetch_list(location=MY_LOCATION, cache_file=CACHE_FILE): """Goes to the default location and returns a python list """ http = urllib3.PoolManager() try: r = http.request("GET", location) raw_data = r.data.decode("utf-8") data = json.loads(raw_data) except (urllib3.exceptions.HTTPError, JSONDecodeError): logger.error("Cannot access Intranet List Location - fetching cache") try: data = json.loads(open(cache_file).readlines()) except (IOError, JSONDecodeError): logger.error("Cache File not found or broken") raise else: with open(cache_file, "w") as f: f.write(raw_data) return data