From 5836d7369006cc3374c13df15d5c0298d7cc2f35 Mon Sep 17 00:00:00 2001 From: "J. Rast" Date: Sat, 7 Oct 2023 22:03:55 +0200 Subject: [PATCH] Simplified the code for loading the usernames / passwords --- withings_sync/sync.py | 49 +++++++++++++++---------------------------- 1 file changed, 17 insertions(+), 32 deletions(-) diff --git a/withings_sync/sync.py b/withings_sync/sync.py index 96c1cef..da305cc 100644 --- a/withings_sync/sync.py +++ b/withings_sync/sync.py @@ -15,43 +15,28 @@ from withings_sync.trainerroad import TrainerRoad from withings_sync.fit import FitEncoderWeight, FitEncoderBloodPressure -try: - with open("/run/secrets/garmin_username", encoding="utf-8") as secret: - GARMIN_USERNAME = secret.read().strip("\n") -except OSError: - GARMIN_USERNAME = "" - -try: - with open("/run/secrets/garmin_password", encoding="utf-8") as secret: - GARMIN_PASSWORD = secret.read().strip("\n") -except OSError: - GARMIN_PASSWORD = "" -dotenv.load_dotenv() - -if "GARMIN_USERNAME" in os.environ: - GARMIN_USERNAME = os.getenv("GARMIN_USERNAME") - -if "GARMIN_PASSWORD" in os.environ: - GARMIN_PASSWORD = os.getenv("GARMIN_PASSWORD") +def load_variable(env_var, secrets_file): + """Load a variable from an environment variable or from a secrets file""" + # Try to read the value from the secrets file. Silently fail if the file + # cannot be read and use an empty value + try: + with open(secrets_file, encoding='utf-8') as secret: + value = secret.read().strip("\n") + except OSError: + value = "" -try: - with open("/run/secrets/trainerroad_username", encoding="utf-8") as secret: - TRAINERROAD_USERNAME = secret.read().strip("\n") -except OSError: - TRAINERROAD_USERNAME = "" + # Load variable from environment if it exists, otherwise use the + # value read from the secrets file. + return os.getenv(env_var, value) -try: - with open("/run/secrets/trainerroad_password", encoding="utf-8") as secret: - TRAINERROAD_PASSWORD = secret.read().strip("\n") -except OSError: - TRAINERROAD_PASSWORD = "" +dotenv.load_dotenv() -if "TRAINERROAD_USERNAME" in os.environ: - TRAINERROAD_USERNAME = os.getenv("TRAINERROAD_USERNAME") +GARMIN_USERNAME = load_variable('GARMIN_USERNAME', "/run/secrets/garmin_username") +GARMIN_PASSWORD = load_variable('GARMIN_PASSWORD', "/run/secrets/garmin_password") +TRAINERROAD_USERNAME = load_variable('TRAINERROAD_USERNAME', "/run/secrets/trainerroad_username") +TRAINERROAD_PASSWORD = load_variable('TRAINERROAD_PASSWORD', "/run/secrets/trainerroad_password") -if "TRAINERROAD_PASSWORD" in os.environ: - TRAINERROAD_PASSWORD = os.getenv("TRAINERROAD_PASSWORD") def get_args():