roc-fnb-server/roc_fnb/util/env_file.py

29 lines
1 KiB
Python

from os import environ
def env_file(key, default_file=KeyError, default=KeyError, default_fn=KeyError):
"""
Return a value from an environment variable or file specified by one.
Checks first for the value specified by key with "_FILE" appended. If that
is found, read from the file there. Otherwise return the value of the
environment variable, the contents of the specified default file, the default
value, or raises KeyError.
"""
if fp := environ.get(f'{key}_FILE'):
with open(fp) as file:
return file.read()
if var := environ.get(key):
return var
if default_file is not KeyError:
try:
with open(default_file) as file:
return file.read()
except FileNotFoundError:
... # fallthrough
if default is not KeyError:
return default
if default_fn is not KeyError:
return default_fn()
raise KeyError(f'no environment variable found ${key} nor {key}_FILE and default was not specified')