From 401808d7d1ab4b8856a265c4564bef8ba09f7be7 Mon Sep 17 00:00:00 2001 From: jo Date: Sat, 15 Jan 2022 18:17:33 +0100 Subject: [PATCH] fix(api): duplicate exception raising and close file --- api/libretime_api/settings.py | 10 +--------- api/libretime_api/utils.py | 21 +++++++++++---------- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/api/libretime_api/settings.py b/api/libretime_api/settings.py index 354eee43b..6be4d1782 100644 --- a/api/libretime_api/settings.py +++ b/api/libretime_api/settings.py @@ -1,6 +1,4 @@ -import configparser import os -import sys from .utils import get_random_string, read_config_file @@ -15,13 +13,7 @@ LIBRETIME_STATIC_ROOT = os.getenv( "LIBRETIME_STATIC_ROOT", "/usr/share/airtime/api", ) - -try: - CONFIG = read_config_file(LIBRETIME_CONFIG_FILEPATH) -except IOError as e: - print(f"Unable to read config file {LIBRETIME_CONFIG_FILEPATH}", file=sys.stderr) - print(e, file=sys.stderr) - CONFIG = configparser.ConfigParser() +CONFIG = read_config_file(LIBRETIME_CONFIG_FILEPATH) # Quick-start development settings - unsuitable for production diff --git a/api/libretime_api/utils.py b/api/libretime_api/utils.py index dc43b3a96..a5773d316 100644 --- a/api/libretime_api/utils.py +++ b/api/libretime_api/utils.py @@ -1,23 +1,24 @@ -import configparser import random import string import sys +from configparser import ConfigParser -def read_config_file(config_path): +def read_config_file(config_filepath): """Parse the application's config file located at config_path.""" - config = configparser.ConfigParser() + config = ConfigParser() try: - config.readfp(open(config_path)) - except IOError as e: + with open(config_filepath, encoding="utf-8") as config_file: + config.read_file(config_file) + except IOError as error: print( - "Failed to open config file at {}: {}".format(config_path, e.strerror), + f"Unable to read config file at {config_filepath}: {error.strerror}", file=sys.stderr, ) - raise e - except Exception as e: - print(e.strerror, file=sys.stderr) - raise e + return ConfigParser() + except Exception as error: + print(error, file=sys.stderr) + raise error return config