Adam Matan Adam Matan - 5 months ago 20
Python Question

Flask: Should my own configuration be added to app.config?

Consider a Flask app which imports a configuration class that generates a configuration from a file (YAML, in this example):

from config import ConfigGenerator
app = Flask(__name__)


What is the right place for the configuration object in a Flask app?

Should it be in the module namespace:

config = ConfigGenerator('/etc/server/config.yaml')


Or in the
app.config
:

app.config['my_config'] = ConfigGenerator('/etc/server/config.yaml')


Or even directly under
app
:

app.myconfig = ConfigGenerator('/etc/server/config.yaml')


I think that all three options would work, but I wonder if there are any style or Flask-specific considerations to take into account.

Answer

The first two options are not much different, other than you now don't have to import your config object separately. In other words, by using app.config you can access the configuration throughout your Flask app wherever you already have access to current_app.

The last option however should not be used, don't add attributes to the Flask object.

Comments