API

class twelvefactor.Config(environ=None)

Bases: object

Config environment parser.

This class allows chosen configuration values to be extracted from the processes environment variables and converted into the relevant types.

parser = Config()

config = parser({
    'DEBUG': {
        'type': bool,
        'default': False,
    },
    'SECRET_KEY': str,
})

The above will populate the config variable with two values, DEBUG will be populated with a bool from the environment variable of the same name, throwing an exception on invalid values and defaulting to False when none is provided, and SECRET_KEY will be a str and throw a ConfigError when no value is found in the environment.

An optional environ param can be passed in order to override the environment.

Parameters:environ (dict) – environment dictionary, defaults to os.environ
__call__(schema)

Parse the environment according to a schema.

Parameters:schema (dict) – the schema to parse
Returns:a dictionary of config values
Return type:dict
get(key, default=<object object>, type_=<class 'str'>, subtype=<class 'str'>, mapper=None)

Parse a value from an environment variable.

>>> os.environ['FOO']
<<< '12345'
>>>
>>> os.environ['BAR']
<<< '1,2,3,4'
>>>
>>> 'BAZ' in os.environ
<<< False
>>>
>>> parser = Config()
>>> parser.get('FOO', type_=int)
<<< 12345
>>>
>>> parser.get('BAR', type_=list, subtype=int)
<<< [1, 2, 3, 4]
>>>
>>> parser.get('BAZ', default='abc123')
<<< 'abc123'
>>>
>>> parser.get('FOO', type_=int, mapper=lambda x: x*10)
<<< 123450
Parameters:
  • key (str) – the key to look up the value under
  • default (object) – default value to return when when no value is present
  • type_ (type) – the type to return or factory function
  • subtype (type) – subtype for iterator types
  • mapper (callable) – a function to post-process the value with
Returns:

the parsed config value

Return type:

object

parse(value, type_=<class 'str'>, subtype=<class 'str'>)

Parse value from string.

Convert value to

>>> parser = Config()
>>> parser.parse('12345', type_=int)
<<< 12345
>>>
>>> parser.parse('1,2,3,4', type_=list, subtype=int)
<<< [1, 2, 3, 4]
Parameters:
  • value (str) – string
  • type_ (type) – the type to return or factory function
  • subtype (str) – subtype for iterator types
Returns:

the parsed config value

Return type:

object

class twelvefactor.ConfigError

Bases: Exception

Exception to throw on configuration errors.

twelvefactor.config