Parsing environment variables in python flask config

It is almost always a good idea to have Flask config values set through the environment variables. It allows to make changes in deployments without having to make any change in code as 12 factors app suggests.

So its very common to have a config file like this:

import os  
env = os.environ  
class Config(object):  
    DATABASE_URI = env('DATABASE_URI','some_default') 
    SOMEOTHER_STRING_VALUE = env('SOMEOTHER_VAR','some_default')

But the problem arises when data types other than a string is needed, or perhaps more complex data type (list, dict) is needed. python-decouple comes handy to solve the problem allowing easy casting and custom parser. A very common usage would be:

from decouple import config  
class Config(object):  
    DEBUG = config('DEBUG',True,cast=bool)

This will allow setting an environment variable easily to a boolean value. A little more complex example with custom parsing would be:

from decouple import config  
class Config(object):  
    SOME_VALUES = config('SOME_LIST','value1,value2',cast=lambda s:s.split(','))

This will set the value of SOME_VALUES to a list of strings with values ['value1','value2']

Here is a more complex example I needed for a project where the values of a config var needed to be a dictionary with values of different types:

myvar = {  
    'key2': 'some string',
    'key3': 123

We can set the environment variable as a comma separated string like follows:

export SOME_VALUES=key1=true,key2=some string,key3=123  

And parse it with decouple with supplying a custom parser to it:

import json  
from decouple import config

def parse(s):  
    def isint(s):
            return False
        return True
    def isfloat(s):
            return False
        return True
    def isbool(s):
        if s.lower() in ['true','false']:
            return True
        return False
    result = {}
    for item in s.split(','):
        key,val = item.split('=')
        if isint(val):
        elif isfloat(val):
        elif isbool(val):
            result[key]=json.loads(val.lower()) # just another way to convert a string to bool
            result[key] = val
    return result

class Config(object):  
    SOME_VALUES = config('SOME_VALUES','key1=true,key2=some string,key3=123,key4=10.5',cast=parse)

Moinul Hossain

Read more posts by this author.