Configuration Handling

Applications need some kind of configuration. There are different settingsyou might want to change depending on the application environment liketoggling the debug mode, setting the secret key, and other suchenvironment-specific things.

The way Flask is designed usually requires the configuration to beavailable when the application starts up. You can hard code theconfiguration in the code, which for many small applications is notactually that bad, but there are better ways.

Independent of how you load your config, there is a config objectavailable which holds the loaded configuration values:The config attribute of the Flaskobject. This is the place where Flask itself puts certain configurationvalues and also where extensions can put their configuration values. Butthis is also where you can have your own configuration.

Configuration Basics

The config is actually a subclass of a dictionary andcan be modified just like any dictionary:

  1. app = Flask(__name__)
  2. app.config['TESTING'] = True

Certain configuration values are also forwarded to theFlask object so you can read and write them from there:

  1. app.testing = True

To update multiple keys at once you can use the dict.update()method:

  1. app.config.update(
  2. TESTING=True,
  3. SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/'
  4. )

Environment and Debug Features

The ENV and DEBUG config values are special because theymay behave inconsistently if changed after the app has begun setting up.In order to set the environment and debug mode reliably, Flask usesenvironment variables.

The environment is used to indicate to Flask, extensions, and otherprograms, like Sentry, what context Flask is running in. It iscontrolled with the FLASK_ENV environment variable anddefaults to production.

Setting FLASK_ENV to development will enable debug mode.flask run will use the interactive debugger and reloader by defaultin debug mode. To control this separately from the environment, use theFLASK_DEBUG flag.

ChangelogChanged in version 1.0: Added FLASK_ENV to control the environment separatelyfrom debug mode. The development environment enables debug mode.
To switch Flask to the development environment and enable debug mode,set FLASK_ENV:
  1. $ export FLASK_ENV=development$ flask run
(On Windows, use set instead of export.)Using the environment variables as described above is recommended. Whileit is possible to set ENV and DEBUG in your config orcode, this is strongly discouraged. They can’t be read early by theflask command, and some systems or extensions may have alreadyconfigured themselves based on a previous value.## Builtin Configuration ValuesThe following configuration values are used internally by Flask:- ENV-What environment the app is running in. Flask and extensions mayenable behaviors based on the environment, such as enabling debugmode. The env attribute maps to this configkey. This is set by the FLASK_ENV environment variable andmay not behave as expected if set in code.Do not enable development when deploying in production.Default: 'production'ChangelogNew in version 1.0.- DEBUG-Whether debug mode is enabled. When using flask run to start thedevelopment server, an interactive debugger will be shown forunhandled exceptions, and the server will be reloaded when codechanges. The debug attribute maps to thisconfig key. This is enabled when ENV is 'development'and is overridden by the FLASK_DEBUG environment variable. Itmay not behave as expected if set in code.Do not enable debug mode when deploying in production.Default: True if ENV is 'development', or Falseotherwise.- TESTING-Enable testing mode. Exceptions are propagated rather than handled by thethe app’s error handlers. Extensions may also change their behavior tofacilitate easier testing. You should enable this in your own tests.Default: False- PROPAGATE_EXCEPTIONS-Exceptions are re-raised rather than being handled by the app’s errorhandlers. If not set, this is implicitly true if TESTING or DEBUGis enabled.Default: None- PRESERVE_CONTEXT_ON_EXCEPTION-Don’t pop the request context when an exception occurs. If not set, thisis true if DEBUG is true. This allows debuggers to introspect therequest data on errors, and should normally not need to be set directly.Default: None- TRAP_HTTP_EXCEPTIONS-If there is no handler for an HTTPException-type exception, re-raise itto be handled by the interactive debugger instead of returning it as asimple error response.Default: False- TRAP_BAD_REQUEST_ERRORS-Trying to access a key that doesn’t exist from request dicts like argsand form will return a 400 Bad Request error page. Enable this to treatthe error as an unhandled exception instead so that you get the interactivedebugger. This is a more specific version of TRAP_HTTP_EXCEPTIONS. Ifunset, it is enabled in debug mode.Default: None- SECRET_KEY-A secret key that will be used for securely signing the session cookieand can be used for any other security related needs by extensions or yourapplication. It should be a long random string of bytes, although unicodeis accepted too. For example, copy the output of this to your config:
  1. $ python -c 'import os; print(os.urandom(16))'b'_5#y2L"F4Q8z\n\xec]/'
Do not reveal the secret key when posting questions or committing code.Default: None- SESSION_COOKIE_NAME-The name of the session cookie. Can be changed in case you already have acookie with the same name.Default: 'session'- SESSION_COOKIE_DOMAIN-The domain match rule that the session cookie will be valid for. If notset, the cookie will be valid for all subdomains of SERVER_NAME.If False, the cookie’s domain will not be set.Default: None- SESSION_COOKIE_PATH-The path that the session cookie will be valid for. If not set, the cookiewill be valid underneath APPLICATION_ROOT or / if that is not set.Default: None- SESSION_COOKIE_HTTPONLY-Browsers will not allow JavaScript access to cookies marked as “HTTP only”for security.Default: True- SESSION_COOKIE_SECURE-Browsers will only send cookies with requests over HTTPS if the cookie ismarked “secure”. The application must be served over HTTPS for this to makesense.Default: False- SESSION_COOKIE_SAMESITE-Restrict how cookies are sent with requests from external sites. Canbe set to 'Lax' (recommended) or 'Strict'.See Set-Cookie options.Default: NoneChangelogNew in version 1.0.- PERMANENT_SESSION_LIFETIME-If session.permanent is true, the cookie’s expiration will be set thisnumber of seconds in the future. Can either be adatetime.timedelta or an int.Flask’s default cookie implementation validates that the cryptographicsignature is not older than this value.Default: timedelta(days=31) (2678400 seconds)- SESSION_REFRESH_EACH_REQUEST-Control whether the cookie is sent with every response whensession.permanent is true. Sending the cookie every time (the default)can more reliably keep the session from expiring, but uses more bandwidth.Non-permanent sessions are not affected.Default: True- USE_X_SENDFILE-When serving files, set the X-Sendfile header instead of serving thedata with Flask. Some web servers, such as Apache, recognize this and servethe data more efficiently. This only makes sense when using such a server.Default: False- SEND_FILE_MAX_AGE_DEFAULT-When serving files, set the cache control max age to this number ofseconds. Can either be a datetime.timedelta or an int.Override this value on a per-file basis usingget_send_file_max_age() on the application or blueprint.Default: timedelta(hours=12) (43200 seconds)- SERVER_NAME-Inform the application what host and port it is bound to. Requiredfor subdomain route matching support.If set, will be used for the session cookie domain ifSESSION_COOKIE_DOMAIN is not set. Modern web browsers willnot allow setting cookies for domains without a dot. To use a domainlocally, add any names that should route to the app to yourhosts file.
  1. 127.0.0.1 localhost.dev
If set, url_for can generate external URLs with only an applicationcontext instead of a request context.Default: None- APPLICATION_ROOT-Inform the application what path it is mounted under by the application /web server. This is used for generating URLs outside the context of arequest (inside a request, the dispatcher is responsible for settingSCRIPT_NAME instead; see Application Dispatchingfor examples of dispatch configuration).Will be used for the session cookie path if SESSION_COOKIE_PATH is notset.Default: '/'- PREFERRED_URL_SCHEME-Use this scheme for generating external URLs when not in a request context.Default: 'http'- MAX_CONTENT_LENGTH-Don’t read more than this many bytes from the incoming request data. If notset and the request does not specify a CONTENT_LENGTH, no data will beread for security.Default: None- JSON_AS_ASCII-Serialize objects to ASCII-encoded JSON. If this is disabled, the JSONwill be returned as a Unicode string, or encoded as UTF-8 byjsonify. This has security implications when rendering the JSON intoJavaScript in templates, and should typically remain enabled.Default: True- JSON_SORT_KEYS-Sort the keys of JSON objects alphabetically. This is useful for cachingbecause it ensures the data is serialized the same way no matter whatPython’s hash seed is. While not recommended, you can disable this for apossible performance improvement at the cost of caching.Default: True- JSONIFY_PRETTYPRINT_REGULAR-jsonify responses will be output with newlines, spaces, and indentationfor easier reading by humans. Always enabled in debug mode.Default: False- JSONIFY_MIMETYPE-The mimetype of jsonify responses.Default: 'application/json'- TEMPLATES_AUTO_RELOAD-Reload templates when they are changed. If not set, it will be enabled indebug mode.Default: None- EXPLAIN_TEMPLATE_LOADING-Log debugging information tracing how a template file was loaded. This canbe useful to figure out why a template was not loaded or the wrong fileappears to be loaded.Default: False- MAX_COOKIE_SIZE-Warn if cookie headers are larger than this many bytes. Defaults to4093. Larger cookies may be silently ignored by browsers. Set to0 to disable the warning.
ChangelogChanged in version 1.0: LOGGER_NAME and LOGGER_HANDLER_POLICY were removed. SeeLogging for information about configuration.Added ENV to reflect the FLASK_ENV environmentvariable.Added SESSION_COOKIE_SAMESITE to control the sessioncookie’s SameSite option.Added MAX_COOKIE_SIZE to control a warning from Werkzeug.New in version 0.11: SESSION_REFRESH_EACH_REQUEST, TEMPLATES_AUTO_RELOAD,LOGGER_HANDLER_POLICY, EXPLAIN_TEMPLATE_LOADINGNew in version 0.10: JSON_AS_ASCII, JSON_SORT_KEYS, JSONIFY_PRETTYPRINT_REGULARNew in version 0.9: PREFERRED_URL_SCHEMENew in version 0.8: TRAP_BAD_REQUEST_ERRORS, TRAP_HTTP_EXCEPTIONS,APPLICATION_ROOT, SESSION_COOKIE_DOMAIN,SESSION_COOKIE_PATH, SESSION_COOKIE_HTTPONLY,SESSION_COOKIE_SECURENew in version 0.7: PROPAGATE_EXCEPTIONS, PRESERVE_CONTEXT_ON_EXCEPTIONNew in version 0.6: MAX_CONTENT_LENGTHNew in version 0.5: SERVER_NAMENew in version 0.4: LOGGER_NAME

Configuring from Files

Configuration becomes more useful if you can store it in a separate file,ideally located outside the actual application package. This makespackaging and distributing your application possible via various packagehandling tools (Deploying with Setuptools) and finally modifying theconfiguration file afterwards.

So a common pattern is this:

  1. app = Flask(__name__)
  2. app.config.from_object('yourapplication.default_settings')
  3. app.config.from_envvar('YOURAPPLICATION_SETTINGS')

This first loads the configuration from theyourapplication.default_settings module and then overrides the valueswith the contents of the file the YOURAPPLICATION_SETTINGSenvironment variable points to. This environment variable can be set onLinux or OS X with the export command in the shell before starting theserver:

  1. $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
  2. $ python run-app.py
  3. * Running on http://127.0.0.1:5000/
  4. * Restarting with reloader...

On Windows systems use the set builtin instead:

  1. > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg

The configuration files themselves are actual Python files. Only valuesin uppercase are actually stored in the config object later on. So makesure to use uppercase letters for your config keys.

Here is an example of a configuration file:

  1. # Example configuration
  2. DEBUG = False
  3. SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'

Make sure to load the configuration very early on, so that extensions havethe ability to access the configuration when starting up. There are othermethods on the config object as well to load from individual files. For acomplete reference, read the Config object’sdocumentation.

Configuring from Environment Variables

In addition to pointing to configuration files using environment variables, youmay find it useful (or necessary) to control your configuration values directlyfrom the environment.

Environment variables can be set on Linux or OS X with the export command inthe shell before starting the server:

  1. $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f'
  2. $ export MAIL_ENABLED=false
  3. $ python run-app.py
  4. * Running on http://127.0.0.1:5000/

On Windows systems use the set builtin instead:

  1. > set SECRET_KEY='5f352379324c22463451387a0aec5d2f'

While this approach is straightforward to use, it is important to remember thatenvironment variables are strings – they are not automatically deserializedinto Python types.

Here is an example of a configuration file that uses environment variables:

  1. import os
  2.  
  3. _mail_enabled = os.environ.get("MAIL_ENABLED", default="true")
  4. MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}
  5.  
  6. SECRET_KEY = os.environ.get("SECRET_KEY")
  7.  
  8. if not SECRET_KEY:
  9. raise ValueError("No SECRET_KEY set for Flask application")

Notice that any value besides an empty string will be interpreted as a booleanTrue value in Python, which requires care if an environment explicitly setsvalues intended to be False.

Make sure to load the configuration very early on, so that extensions have theability to access the configuration when starting up. There are other methodson the config object as well to load from individual files. For a completereference, read the Config class documentation.

Configuration Best Practices

The downside with the approach mentioned earlier is that it makes testinga little harder. There is no single 100% solution for this problem ingeneral, but there are a couple of things you can keep in mind to improvethat experience:

  • Create your application in a function and register blueprints on it.That way you can create multiple instances of your application withdifferent configurations attached which makes unit testing a loteasier. You can use this to pass in configuration as needed.

  • Do not write code that needs the configuration at import time. If youlimit yourself to request-only accesses to the configuration you canreconfigure the object later on as needed.

Development / Production

Most applications need more than one configuration. There should be atleast separate configurations for the production server and the one usedduring development. The easiest way to handle this is to use a defaultconfiguration that is always loaded and part of the version control, and aseparate configuration that overrides the values as necessary as mentionedin the example above:

  1. app = Flask(__name__)
  2. app.config.from_object('yourapplication.default_settings')
  3. app.config.from_envvar('YOURAPPLICATION_SETTINGS')

Then you just have to add a separate config.py file and exportYOURAPPLICATION_SETTINGS=/path/to/config.py and you are done. Howeverthere are alternative ways as well. For example you could use imports orsubclassing.

What is very popular in the Django world is to make the import explicit inthe config file by adding from yourapplication.defaultsettingsimport * to the top of the file and then overriding the changes by hand.You could also inspect an environment variable likeYOURAPPLICATION_MODE and set that to _production, development etcand import different hard-coded files based on that.

An interesting pattern is also to use classes and inheritance forconfiguration:

  1. class Config(object):
  2. DEBUG = False
  3. TESTING = False
  4. DATABASE_URI = 'sqlite:///:memory:'
  5.  
  6. class ProductionConfig(Config):
  7. DATABASE_URI = 'mysql://[email protected]/foo'
  8.  
  9. class DevelopmentConfig(Config):
  10. DEBUG = True
  11.  
  12. class TestingConfig(Config):
  13. TESTING = True

To enable such a config you just have to call intofrom_object():

  1. app.config.from_object('configmodule.ProductionConfig')

Note that from_object() does not instantiate the classobject. If you need to instantiate the class, such as to access a property,then you must do so before calling from_object():

  1. from configmodule import ProductionConfig
  2. app.config.from_object(ProductionConfig())
  3.  
  4. # Alternatively, import via string:
  5. from werkzeug.utils import import_string
  6. cfg = import_string('configmodule.ProductionConfig')()
  7. app.config.from_object(cfg)

Instantiating the configuration object allows you to use @property inyour configuration classes:

  1. class Config(object):
  2. """Base config, uses staging database server."""
  3. DEBUG = False
  4. TESTING = False
  5. DB_SERVER = '192.168.1.56'
  6.  
  7. @property
  8. def DATABASE_URI(self): # Note: all caps
  9. return 'mysql://[email protected]{}/foo'.format(self.DB_SERVER)
  10.  
  11. class ProductionConfig(Config):
  12. """Uses production database server."""
  13. DB_SERVER = '192.168.19.32'
  14.  
  15. class DevelopmentConfig(Config):
  16. DB_SERVER = 'localhost'
  17. DEBUG = True
  18.  
  19. class TestingConfig(Config):
  20. DB_SERVER = 'localhost'
  21. DEBUG = True
  22. DATABASE_URI = 'sqlite:///:memory:'

There are many different ways and it’s up to you how you want to manageyour configuration files. However here a list of good recommendations:

  • Keep a default configuration in version control. Either populate theconfig with this default configuration or import it in your ownconfiguration files before overriding values.

  • Use an environment variable to switch between the configurations.This can be done from outside the Python interpreter and makesdevelopment and deployment much easier because you can quickly andeasily switch between different configs without having to touch thecode at all. If you are working often on different projects you caneven create your own script for sourcing that activates a virtualenvand exports the development configuration for you.

  • Use a tool like fabric in production to push code andconfigurations separately to the production server(s). For somedetails about how to do that, head over to theDeploying with Fabric pattern.

Instance Folders

Changelog

New in version 0.8.

Flask 0.8 introduces instance folders. Flask for a long time made itpossible to refer to paths relative to the application’s folder directly(via Flask.root_path). This was also how many developers loadedconfigurations stored next to the application. Unfortunately however thisonly works well if applications are not packages in which case the rootpath refers to the contents of the package.

With Flask 0.8 a new attribute was introduced:Flask.instance_path. It refers to a new concept called the“instance folder”. The instance folder is designed to not be underversion control and be deployment specific. It’s the perfect place todrop things that either change at runtime or configuration files.

You can either explicitly provide the path of the instance folder whencreating the Flask application or you can let Flask autodetect theinstance folder. For explicit configuration use the _instance_path_parameter:

  1. app = Flask(__name__, instance_path='/path/to/instance/folder')

Please keep in mind that this path must be absolute when provided.

If the instance_path parameter is not provided the following defaultlocations are used:

  • Uninstalled module:
  1. /myapp.py
  2. /instance
  • Uninstalled package:
  1. /myapp
  2. /__init__.py
  3. /instance
  • Installed module or package:
  1. $PREFIX/lib/python2.X/site-packages/myapp
  2. $PREFIX/var/myapp-instance

$PREFIX is the prefix of your Python installation. This can be/usr or the path to your virtualenv. You can print the value ofsys.prefix to see what the prefix is set to.

Since the config object provided loading of configuration files fromrelative filenames we made it possible to change the loading via filenamesto be relative to the instance path if wanted. The behavior of relativepaths in config files can be flipped between “relative to the applicationroot” (the default) to “relative to instance folder” via theinstance_relative_config switch to the application constructor:

  1. app = Flask(__name__, instance_relative_config=True)

Here is a full example of how to configure Flask to preload the configfrom a module and then override the config from a file in the instancefolder if it exists:

  1. app = Flask(__name__, instance_relative_config=True)
  2. app.config.from_object('yourapplication.default_settings')
  3. app.config.from_pyfile('application.cfg', silent=True)

The path to the instance folder can be found via theFlask.instance_path. Flask also provides a shortcut to open afile from the instance folder with Flask.open_instance_resource().

Example usage for both:

  1. filename = os.path.join(app.instance_path, 'application.cfg')
  2. with open(filename) as f:
  3. config = f.read()
  4.  
  5. # or via open_instance_resource:
  6. with app.open_instance_resource('application.cfg') as f:
  7. config = f.read()