Environment Settings, overload helper
I am working with environment variables because the current application I am building is a 12 factor application adherent and while messing with the .env files and or actual os/user environment variables it can get a bit confusing so I wrote this helper class to load the application variables in an ordered manner with the dotenv library.
import dataclasses
import os
from dotenv import load_dotenv, find_dotenv, dotenv_values
import structlog
structlog.configure(processors=[structlog.processors.JSONRenderer()])
from structlog import BoundLogger
log: BoundLogger = structlog.get_logger(__name__)
@dataclasses.dataclass(frozen=True, kw_only=True)
class EnvSettings:
@staticmethod
def variables() -> frozenset[str]:
return frozenset(['ENV', 'EXPORT_KEY'])
@staticmethod
def validation_summary(env_file_path: str | None = None) -> list[str]:
details = []
for item in EnvSettings.variables():
setting = EnvSettings.getenv(item, env_file_path)
if setting is None:
details.append(f'Environment variable {item} is missing')
elif len(setting.strip()) == 0:
if len(setting) > 0:
details.append(f'Environment variable {item} is blank')
else:
details.append(f'Environment variable {item} is whitespace')
else:
log.info(f'Environment variable {item} is set to {setting}')
return details
@staticmethod
def getenv(key_name: str, env_file_path: str | None = None) -> str | None:
env_file = env_file_path if env_file_path is not None else find_dotenv()
load_dotenv(env_file)
current = {**dotenv_values(find_dotenv()), **os.environ}
if key_name in current:
return current[key_name]
return NoneFrom this
setting1 = os.getenv('setting1')To this
setting1 = EnvSettings.getenv('setting1')To see the values on script load do this
for setting in EnvSettings.validation_summary():
print(setting)
if __name__ == '__main__':
print('Start')Enjoy