Python configuration management for flask based application

Sairam Krish
2 min readFeb 3, 2020

If we are using flask, then we could do environment specific config management like this :

project folder structure

config/
default.py
production.py
development.py
instance/
config.py
myapp/
__init__.py

Config file structure like properties file

# default.py

DEBUG = False
SQLALCHEMY_ECHO = False

Though the config files are python files, internally the content is more like a properties file. This gives us capability to volume mount required configurations to docker containers with a easy to read and modify format for any non-developers.

Initialization

During app initialization.,

# app/__init__.py

app = Flask(__name__, instance_relative_config=True)

# Load the default configuration
app.config.from_object(‘config.default’)

# Load the configuration from the instance folder
app.config.from_pyfile(‘config.py’)

# Load the file specific to environment based on ENV variable
# Variables defined here will override those in the default configuration
app.config.from_object(‘config.’+os.getenv(“ENV”))

Running the application

While running the application:

# start.sh
# ENV should match the file name
ENV=production python run.py

The above method is my preferred way. This method is based on best practices described here with few modifications like file name based on environment variable.

Why not use from_json

Instead of python based configuration, we could have json file and we could do the following:

app.config.from_json('testapp/config/default.json')

But the problem is internally it uses from_mapping method. So it will load first level of properties declared in the json. It will not load nested configurations. By having it as a json, it may be misleading to users what to expect and how it behaves internally. As a best practice, keeping it as a python file, avoids giving wrong idea to end users.

Alternate options:

--

--