Skip to content

Commit

Permalink
Merge pull request #142 from jrast/simplified-var-loading
Browse files Browse the repository at this point in the history
Simplified the code for loading the usernames / passwords
  • Loading branch information
longstone authored Oct 7, 2023
2 parents 99f9186 + 5836d73 commit 383bf00
Showing 1 changed file with 17 additions and 32 deletions.
49 changes: 17 additions & 32 deletions withings_sync/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down

0 comments on commit 383bf00

Please sign in to comment.