# Handling configuration file in a flask webapp

**URL:** <https://discuss.python.org/t/handling-configuration-file-in-a-flask-webapp/60048>\
**Category:** Python Help\
**Tags:** help\
**Created:** [August 5, 2024, 8:28pm UTC](https://discuss.python.org/t/handling-configuration-file-in-a-flask-webapp/60048 "2024-08-05T20:28:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Monarch](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/monarch/32/18530_2.png) [@Monarch](https://discuss.python.org/u/Monarch)\
**Post date:** [August 5, 2024, 8:28pm UTC](https://discuss.python.org/t/handling-configuration-file-in-a-flask-webapp/60048/1 "2024-08-05T20:28:46Z")

</div>

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

```python
# 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:

```python
# 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.

---

<div class="post-metadata">

**Author:** ![Rosuav](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/rosuav/32/3429_2.png) [@Rosuav](https://discuss.python.org/u/Rosuav)\
**Post date:** [August 5, 2024, 11:45pm UTC](https://discuss.python.org/t/handling-configuration-file-in-a-flask-webapp/60048/2 "2024-08-05T23:45:31Z")

</div>

> [@Monarch](#):
>
> 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:

```python
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.)

---

<div class="post-metadata">

**Author:** ![Monarch](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/monarch/32/18530_2.png) [@Monarch](https://discuss.python.org/u/Monarch)\
**Post date:** [August 6, 2024, 1:38am UTC](https://discuss.python.org/t/handling-configuration-file-in-a-flask-webapp/60048/3 "2024-08-06T01:38:51Z")

</div>

I’ll do just that, thank you!
