Flask Series: Configuration

Thursday, Apr 23, 2015 08:29 · 372 words · 2 minutes read python flask flask series

Flask Series

  1. Prepare the Environment
  2. Structure the Application
  3. Application Configuration
  4. Templating
  5. Model
  6. Testing
  7. Views and Web Forms
  8. Error Management
  9. Security
  10. Optimizations
  11. Healthcheck and Monitoring
  12. Internationalization
  13. Deployment
Each application needs a configuration. Flask allows developers to implement their application configuration using several different approaches:

  • file-based
  • object-based
  • environment-variable-based
  • instance-folders-based

Regardless of what approach developer chooses for her/his Flask application configuration, all configuration values are loaded on the config attribute(configuration dictionary) of the Flask application object:

There is a list of configuration values, used internally by Flask. Note that Flask expects configuration to be available when the application starts up.

File-based configuration

Flask allows developers to store their configuration in separate files and load it from them. The configuration file uses INI file syntax – name/value pairs in a plain text file, separated by an equal sign (“=”).

Object-based configuration

Good pattern to follow is to use classes for your Flask application configuration:

and to use this configuration, the from_object method should be used:

EnvVars-based configuration

The application can be configured based on configuration file, which is specified by a environment variable:

here the FLASK_CONFIG_FILE environment variable points to the configuration file.

Instance-based configuration

Since version 0.8 Flask provides one more configuration option – instance folders. The instance folder is designed not to be under source control and could store sensitive information. This instance folder should be directly deployed on the production server. To be able to use it, the instance_path of the Flask object should be specified:

or use it as relative path, where we have instance folder under our application folder.

Now you are ready to configure your application based on the instance folders mechanism, where the flask.cfg is stored either under the instance_path (1) or under the instance folder (2)

Best Practice

Good practice is to have a default configuration, which is under source control and to override it with sensitive and specific information kept in instance folders. For the default configuration you could use object-based configuration hierarchy(described in Object-based configuration section) and to manage which configuration object to load via environment variables:

In the next blog post I will describe how to use templates in your Flask project.

The complete demo application, described in this blog post, can be found here.
comments powered by Disqus