Load configuration

As a Django user, you manage configuration as you like: as Python modules, as JSON or YAML files, as environment variables... Do whatever integrates best with your deployment workflow and your team.

As a non Django user (such as a member of the Ops team), you may appreciate putting configuration in configuration files or in environment variables. Not in Python code.

This document explains how django-confit can help Django users load configuration from various locations and formats.


django_confit.loaders.load_mapping(input, prefix='')

Convert mapping of {key: string} to {key: complex type}.

This function makes it possible (and easy) to load complex types from single-level key-value stores, such as environment variables or INI files.

Of course, both flat and nested mappings are supported:

>>> from django_confit import load_mapping
>>> flat_mapping = {'DEBUG': 'True', 'SECRET_KEY': 'not a secret'}
>>> output = load_mapping(flat_mapping)
>>> output == flat_mapping
>>> nested_mapping = {'DATABASES': {'USER': 'me', 'HOST': 'localhost'}}
>>> output = load_mapping(nested_mapping)
>>> output == nested_mapping

Values can be complex types (sequences, mappings) using JSON or YAML. Keys using ”.json” or ”.yaml” suffix are automatically decoded:

>>> nested_mapping = {
...     'DATABASES.yaml': 'ENGINE: sqlite3',
... }
>>> output = load_mapping(nested_mapping)
>>> output['DATABASES'] == {'ENGINE': 'sqlite3'}

You can use optional prefix argument to load only a subset of mapping:

>>> mapping = {'YES_ONE': '1', 'NO_TWO': '2'}
>>> load_mapping(mapping, prefix='YES_')
{'ONE': '1'}



Return module’s globals as a dict.

>>> from django_confit import load_module
>>> settings = load_module('django.conf.global_settings')
>>> settings['DATABASES']

It does not load “protected” and “private” attributes (those with underscores).

>>> '__name__' in settings



Return mapping from file object, using name attr to guess format.

Supported file formats are JSON and YAML. The lowercase extension is used to guess the file type.

>>> from django_confit import load_file
>>> from six.moves import StringIO
>>> file_obj = StringIO('SOME_LIST: [a, b, c]')
>>> file_obj.name = 'something.yaml'
>>> load_file(file_obj) == {
...     'SOME_LIST': ['a', 'b', 'c'],
... }