Handling configuration file in a flask webapp

I have a flask webapp that loads config upon startup from a hardcoded path like so:

# configuration.py
import sys
from pathlib import Path
from yaml import safe_load

prod = Path(__file__).resolve().parent.parent / "conf.yml"
dev = Path(__file__).resolve().parent.parent / "dev_conf.yml"

try:
    if "pytest" in sys.modules:
        config = safe_load(prod)
    else:
        config = safe_load(dev)
except ValueError:
    raise SystemExit("Failed to load config")

This config var is then imported and used across all the other files. E.g:

# some_other_module.py
from .configuration import config

print(f"hello {config["email"]}")

I wanna improve this because I have a feeling this isn’t the best way to achieve this. How would I go about it? My first guess is that instead of loading a hardcoded path, load it from an env var.

Yes, that’d be an excellent idea. However, DON’T just take an environment variable and use that as a file name. Instead, have a specific list of keywords (eg prod, dev) and have those map to your file names:

confs = {
    "prod": "conf.yml",
    "dev": "dev_conf.yml"
}

and then, if the environment variable matches one of them, you use that config. (Suggestion: Default to a dev config, not a production one. It’s usually more useful.)

1 Like

I’ll do just that, thank you!