Search code examples
djangoconfigpyyaml

How to read external config file in Django and have it available everywhere


I want to define an external config file, for example, in Yaml. How can I read it in once at initialization and then have it available everywhere, without having to re-read the file each time?

For example, if I put this in apps.py

def ready(self)
    config = yaml.safe_load(open("config.yml"))

How do I reference this from, for example, views.py


Solution

  • You can upload your file to the settings and then access it from everywhere. Change in settings.py:

    # settings.py
    BASE_URL = Path(__file__).resolve().parent.parent
    DEBUG = True
    ...
    MY_YAML = yaml.safe_load((BASE_URL / 'config.yml').read_text())
    ...
    

    After that, you will be able to refer to it from everywhere in project:

    # somethere in project xyz.py
    from django.conf import settings
    ...
    yaml = settings.MY_YAML
    ...