Skip to content
Myr

config.rst

This file

Path

docs/config.rst

465 lines · 21.4 KiB

Last changed by

Fix rST rendering of env var (#2085)Jannis Leidelbefore adoption4cf4229

History of this file

Take it

1.. _config:23Configuration Handling4======================56.. versionadded:: 0.378Applications need some kind of configuration.  There are different settings9you might want to change depending on the application environment like10toggling the debug mode, setting the secret key, and other such11environment-specific things.1213The way Flask is designed usually requires the configuration to be14available when the application starts up.  You can hardcode the15configuration in the code, which for many small applications is not16actually that bad, but there are better ways.1718Independent of how you load your config, there is a config object19available which holds the loaded configuration values:20The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`21object.  This is the place where Flask itself puts certain configuration22values and also where extensions can put their configuration values.  But23this is also where you can have your own configuration.2425Configuration Basics26--------------------2728The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and29can be modified just like any dictionary::3031    app = Flask(__name__)32    app.config['DEBUG'] = True3334Certain configuration values are also forwarded to the35:attr:`~flask.Flask` object so you can read and write them from there::3637    app.debug = True3839To update multiple keys at once you can use the :meth:`dict.update`40method::4142    app.config.update(43        DEBUG=True,44        SECRET_KEY='...'45    )4647Builtin Configuration Values48----------------------------4950The following configuration values are used internally by Flask:5152.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|5354================================= =========================================55``DEBUG``                         enable/disable debug mode56``TESTING``                       enable/disable testing mode57``PROPAGATE_EXCEPTIONS``          explicitly enable or disable the58                                  propagation of exceptions.  If not set or59                                  explicitly set to ``None`` this is60                                  implicitly true if either ``TESTING`` or61                                  ``DEBUG`` is true.62``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in63                                  debug mode the request context is not64                                  popped on exceptions to enable debuggers65                                  to introspect the data.  This can be66                                  disabled by this key.  You can also use67                                  this setting to force-enable it for non68                                  debug execution which might be useful to69                                  debug production applications (but also70                                  very risky).71``SECRET_KEY``                    the secret key72``SESSION_COOKIE_NAME``           the name of the session cookie73``SESSION_COOKIE_DOMAIN``         the domain for the session cookie.  If74                                  this is not set, the cookie will be75                                  valid for all subdomains of76                                  ``SERVER_NAME``.77``SESSION_COOKIE_PATH``           the path for the session cookie.  If78                                  this is not set the cookie will be valid79                                  for all of ``APPLICATION_ROOT`` or if80                                  that is not set for ``'/'``.81``SESSION_COOKIE_HTTPONLY``       controls if the cookie should be set82                                  with the httponly flag.  Defaults to83                                  ``True``.84``SESSION_COOKIE_SECURE``         controls if the cookie should be set85                                  with the secure flag.  Defaults to86                                  ``False``.87``PERMANENT_SESSION_LIFETIME``    the lifetime of a permanent session as88                                  :class:`datetime.timedelta` object.89                                  Starting with Flask 0.8 this can also be90                                  an integer representing seconds.91``SESSION_REFRESH_EACH_REQUEST``  this flag controls how permanent92                                  sessions are refreshed.  If set to ``True``93                                  (which is the default) then the cookie94                                  is refreshed each request which95                                  automatically bumps the lifetime.  If96                                  set to ``False`` a `set-cookie` header is97                                  only sent if the session is modified.98                                  Non permanent sessions are not affected99                                  by this.100``USE_X_SENDFILE``                enable/disable x-sendfile101``LOGGER_NAME``                   the name of the logger102``LOGGER_HANDLER_POLICY``         the policy of the default logging103                                  handler.  The default is ``'always'``104                                  which means that the default logging105                                  handler is always active.  ``'debug'``106                                  will only activate logging in debug107                                  mode, ``'production'`` will only log in108                                  production and ``'never'`` disables it109                                  entirely.110``SERVER_NAME``                   the name and port number of the server.111                                  Required for subdomain support (e.g.:112                                  ``'myapp.dev:5000'``)  Note that113                                  localhost does not support subdomains so114                                  setting this to “localhost” does not115                                  help.  Setting a ``SERVER_NAME`` also116                                  by default enables URL generation117                                  without a request context but with an118                                  application context.119``APPLICATION_ROOT``              If the application does not occupy120                                  a whole domain or subdomain this can121                                  be set to the path where the application122                                  is configured to live.  This is for123                                  session cookie as path value.  If124                                  domains are used, this should be125                                  ``None``.126``MAX_CONTENT_LENGTH``            If set to a value in bytes, Flask will127                                  reject incoming requests with a128                                  content length greater than this by129                                  returning a 413 status code.130``SEND_FILE_MAX_AGE_DEFAULT``     Default cache control max age to use with131                                  :meth:`~flask.Flask.send_static_file` (the132                                  default static file handler) and133                                  :func:`~flask.send_file`, as134                                  :class:`datetime.timedelta` or as seconds.135                                  Override this value on a per-file136                                  basis using the137                                  :meth:`~flask.Flask.get_send_file_max_age`138                                  hook on :class:`~flask.Flask` or139                                  :class:`~flask.Blueprint`,140                                  respectively. Defaults to 43200 (12 hours).141``TRAP_HTTP_EXCEPTIONS``          If this is set to ``True`` Flask will142                                  not execute the error handlers of HTTP143                                  exceptions but instead treat the144                                  exception like any other and bubble it145                                  through the exception stack.  This is146                                  helpful for hairy debugging situations147                                  where you have to find out where an HTTP148                                  exception is coming from.149``TRAP_BAD_REQUEST_ERRORS``       Werkzeug's internal data structures that150                                  deal with request specific data will151                                  raise special key errors that are also152                                  bad request exceptions.  Likewise many153                                  operations can implicitly fail with a154                                  BadRequest exception for consistency.155                                  Since it's nice for debugging to know156                                  why exactly it failed this flag can be157                                  used to debug those situations.  If this158                                  config is set to ``True`` you will get159                                  a regular traceback instead.160``PREFERRED_URL_SCHEME``          The URL scheme that should be used for161                                  URL generation if no URL scheme is162                                  available.  This defaults to ``http``.163``JSON_AS_ASCII``                 By default Flask serialize object to164                                  ascii-encoded JSON.  If this is set to165                                  ``False`` Flask will not encode to ASCII166                                  and output strings as-is and return167                                  unicode strings.  ``jsonify`` will168                                  automatically encode it in ``utf-8``169                                  then for transport for instance.170``JSON_SORT_KEYS``                By default Flask will serialize JSON171                                  objects in a way that the keys are172                                  ordered.  This is done in order to173                                  ensure that independent of the hash seed174                                  of the dictionary the return value will175                                  be consistent to not trash external HTTP176                                  caches.  You can override the default177                                  behavior by changing this variable.178                                  This is not recommended but might give179                                  you a performance improvement on the180                                  cost of cacheability.181``JSONIFY_PRETTYPRINT_REGULAR``   If this is set to ``True`` (the default)182                                  jsonify responses will be pretty printed183                                  if they are not requested by an184                                  XMLHttpRequest object (controlled by185                                  the ``X-Requested-With`` header)186``JSONIFY_MIMETYPE``              MIME type used for jsonify responses.187``TEMPLATES_AUTO_RELOAD``         Whether to check for modifications of188                                  the template source and reload it189                                  automatically. By default the value is190                                  ``None`` which means that Flask checks191                                  original file only in debug mode.192``EXPLAIN_TEMPLATE_LOADING``      If this is enabled then every attempt to193                                  load a template will write an info194                                  message to the logger explaining the195                                  attempts to locate the template.  This196                                  can be useful to figure out why197                                  templates cannot be found or wrong198                                  templates appear to be loaded.199================================= =========================================200201.. admonition:: More on ``SERVER_NAME``202203   The ``SERVER_NAME`` key is used for the subdomain support.  Because204   Flask cannot guess the subdomain part without the knowledge of the205   actual server name, this is required if you want to work with206   subdomains.  This is also used for the session cookie.207208   Please keep in mind that not only Flask has the problem of not knowing209   what subdomains are, your web browser does as well.  Most modern web210   browsers will not allow cross-subdomain cookies to be set on a211   server name without dots in it.  So if your server name is212   ``'localhost'`` you will not be able to set a cookie for213   ``'localhost'`` and every subdomain of it.  Please choose a different214   server name in that case, like ``'myapplication.local'`` and add215   this name + the subdomains you want to use into your host config216   or setup a local `bind`_.217218.. _bind: https://www.isc.org/downloads/bind/219220.. versionadded:: 0.4221   ``LOGGER_NAME``222223.. versionadded:: 0.5224   ``SERVER_NAME``225226.. versionadded:: 0.6227   ``MAX_CONTENT_LENGTH``228229.. versionadded:: 0.7230   ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``231232.. versionadded:: 0.8233   ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,234   ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,235   ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,236   ``SESSION_COOKIE_SECURE``237238.. versionadded:: 0.9239   ``PREFERRED_URL_SCHEME``240241.. versionadded:: 0.10242   ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``243244.. versionadded:: 0.11245   ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,246   ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``247248Configuring from Files249----------------------250251Configuration becomes more useful if you can store it in a separate file,252ideally located outside the actual application package. This makes253packaging and distributing your application possible via various package254handling tools (:ref:`distribute-deployment`) and finally modifying the255configuration file afterwards.256257So a common pattern is this::258259    app = Flask(__name__)260    app.config.from_object('yourapplication.default_settings')261    app.config.from_envvar('YOURAPPLICATION_SETTINGS')262263This first loads the configuration from the264`yourapplication.default_settings` module and then overrides the values265with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`266environment variable points to.  This environment variable can be set on267Linux or OS X with the export command in the shell before starting the268server::269270    $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg271    $ python run-app.py272     * Running on http://127.0.0.1:5000/273     * Restarting with reloader...274275On Windows systems use the `set` builtin instead::276277    >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg278279The configuration files themselves are actual Python files.  Only values280in uppercase are actually stored in the config object later on.  So make281sure to use uppercase letters for your config keys.282283Here is an example of a configuration file::284285    # Example configuration286    DEBUG = False287    SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'288289Make sure to load the configuration very early on, so that extensions have290the ability to access the configuration when starting up.  There are other291methods on the config object as well to load from individual files.  For a292complete reference, read the :class:`~flask.Config` object's293documentation.294295296Configuration Best Practices297----------------------------298299The downside with the approach mentioned earlier is that it makes testing300a little harder.  There is no single 100% solution for this problem in301general, but there are a couple of things you can keep in mind to improve302that experience:3033041.  Create your application in a function and register blueprints on it.305    That way you can create multiple instances of your application with306    different configurations attached which makes unittesting a lot307    easier.  You can use this to pass in configuration as needed.3083092.  Do not write code that needs the configuration at import time.  If you310    limit yourself to request-only accesses to the configuration you can311    reconfigure the object later on as needed.312313.. _config-dev-prod:314315Development / Production316------------------------317318Most applications need more than one configuration.  There should be at319least separate configurations for the production server and the one used320during development.  The easiest way to handle this is to use a default321configuration that is always loaded and part of the version control, and a322separate configuration that overrides the values as necessary as mentioned323in the example above::324325    app = Flask(__name__)326    app.config.from_object('yourapplication.default_settings')327    app.config.from_envvar('YOURAPPLICATION_SETTINGS')328329Then you just have to add a separate :file:`config.py` file and export330``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done.  However331there are alternative ways as well.  For example you could use imports or332subclassing.333334What is very popular in the Django world is to make the import explicit in335the config file by adding ``from yourapplication.default_settings336import *`` to the top of the file and then overriding the changes by hand.337You could also inspect an environment variable like338``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc339and import different hardcoded files based on that.340341An interesting pattern is also to use classes and inheritance for342configuration::343344    class Config(object):345        DEBUG = False346        TESTING = False347        DATABASE_URI = 'sqlite://:memory:'348349    class ProductionConfig(Config):350        DATABASE_URI = 'mysql://user@localhost/foo'351352    class DevelopmentConfig(Config):353        DEBUG = True354355    class TestingConfig(Config):356        TESTING = True357358To enable such a config you just have to call into359:meth:`~flask.Config.from_object`::360361    app.config.from_object('configmodule.ProductionConfig')362363There are many different ways and it's up to you how you want to manage364your configuration files.  However here a list of good recommendations:365366-   Keep a default configuration in version control.  Either populate the367    config with this default configuration or import it in your own368    configuration files before overriding values.369-   Use an environment variable to switch between the configurations.370    This can be done from outside the Python interpreter and makes371    development and deployment much easier because you can quickly and372    easily switch between different configs without having to touch the373    code at all.  If you are working often on different projects you can374    even create your own script for sourcing that activates a virtualenv375    and exports the development configuration for you.376-   Use a tool like `fabric`_ in production to push code and377    configurations separately to the production server(s).  For some378    details about how to do that, head over to the379    :ref:`fabric-deployment` pattern.380381.. _fabric: http://www.fabfile.org/382383384.. _instance-folders:385386Instance Folders387----------------388389.. versionadded:: 0.8390391Flask 0.8 introduces instance folders.  Flask for a long time made it392possible to refer to paths relative to the application's folder directly393(via :attr:`Flask.root_path`).  This was also how many developers loaded394configurations stored next to the application.  Unfortunately however this395only works well if applications are not packages in which case the root396path refers to the contents of the package.397398With Flask 0.8 a new attribute was introduced:399:attr:`Flask.instance_path`.  It refers to a new concept called the400“instance folder”.  The instance folder is designed to not be under401version control and be deployment specific.  It's the perfect place to402drop things that either change at runtime or configuration files.403404You can either explicitly provide the path of the instance folder when405creating the Flask application or you can let Flask autodetect the406instance folder.  For explicit configuration use the `instance_path`407parameter::408409    app = Flask(__name__, instance_path='/path/to/instance/folder')410411Please keep in mind that this path *must* be absolute when provided.412413If the `instance_path` parameter is not provided the following default414locations are used:415416-   Uninstalled module::417418        /myapp.py419        /instance420421-   Uninstalled package::422423        /myapp424            /__init__.py425        /instance426427-   Installed module or package::428429        $PREFIX/lib/python2.X/site-packages/myapp430        $PREFIX/var/myapp-instance431432    ``$PREFIX`` is the prefix of your Python installation.  This can be433    ``/usr`` or the path to your virtualenv.  You can print the value of434    ``sys.prefix`` to see what the prefix is set to.435436Since the config object provided loading of configuration files from437relative filenames we made it possible to change the loading via filenames438to be relative to the instance path if wanted.  The behavior of relative439paths in config files can be flipped between “relative to the application440root” (the default) to “relative to instance folder” via the441`instance_relative_config` switch to the application constructor::442443    app = Flask(__name__, instance_relative_config=True)444445Here is a full example of how to configure Flask to preload the config446from a module and then override the config from a file in the config447folder if it exists::448449    app = Flask(__name__, instance_relative_config=True)450    app.config.from_object('yourapplication.default_settings')451    app.config.from_pyfile('application.cfg', silent=True)452453The path to the instance folder can be found via the454:attr:`Flask.instance_path`.  Flask also provides a shortcut to open a455file from the instance folder with :meth:`Flask.open_instance_resource`.456457Example usage for both::458459    filename = os.path.join(app.instance_path, 'application.cfg')460    with open(filename) as f:461        config = f.read()462463    # or via open_instance_resource:464    with app.open_instance_resource('application.cfg') as f:465        config = f.read()