Skip to content
Myr

config.rst

This file

Path

docs/config.rst

839 lines · 28.3 KiB

Last changed by

Merge branch 'stable'David Lordbefore adoption2ac8988

History of this file

Take it

1Configuration Handling2======================34Applications need some kind of configuration.  There are different settings5you might want to change depending on the application environment like6toggling the debug mode, setting the secret key, and other such7environment-specific things.89The way Flask is designed usually requires the configuration to be10available when the application starts up.  You can hard code the11configuration in the code, which for many small applications is not12actually that bad, but there are better ways.1314Independent of how you load your config, there is a config object15available which holds the loaded configuration values:16The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`17object.  This is the place where Flask itself puts certain configuration18values and also where extensions can put their configuration values.  But19this is also where you can have your own configuration.202122Configuration Basics23--------------------2425The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and26can be modified just like any dictionary::2728    app = Flask(__name__)29    app.config['TESTING'] = True3031Certain configuration values are also forwarded to the32:attr:`~flask.Flask` object so you can read and write them from there::3334    app.testing = True3536To update multiple keys at once you can use the :meth:`dict.update`37method::3839    app.config.update(40        TESTING=True,41        SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'42    )434445Debug Mode46----------4748The :data:`DEBUG` config value is special because it may behave inconsistently if49changed after the app has begun setting up. In order to set debug mode reliably, use the50``--debug`` option on the ``flask`` or ``flask run`` command. ``flask run`` will use the51interactive debugger and reloader by default in debug mode.5253.. code-block:: text5455    $ flask --app hello run --debug5657Using the option is recommended. While it is possible to set :data:`DEBUG` in your58config or code, this is strongly discouraged. It can't be read early by the59``flask run`` command, and some systems or extensions may have already configured60themselves based on a previous value.616263Builtin Configuration Values64----------------------------6566The following configuration values are used internally by Flask:6768.. py:data:: DEBUG6970    Whether debug mode is enabled. When using ``flask run`` to start the development71    server, an interactive debugger will be shown for unhandled exceptions, and the72    server will be reloaded when code changes. The :attr:`~flask.Flask.debug` attribute73    maps to this config key. This is set with the ``FLASK_DEBUG`` environment variable.74    It may not behave as expected if set in code.7576    **Do not enable debug mode when deploying in production.**7778    Default: ``False``7980.. py:data:: TESTING8182    Enable testing mode. Exceptions are propagated rather than handled by83    the app's error handlers. Extensions may also change their behavior to84    facilitate easier testing. You should enable this in your own tests.8586    Default: ``False``8788.. py:data:: PROPAGATE_EXCEPTIONS8990    Exceptions are re-raised rather than being handled by the app's error91    handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG``92    is enabled.9394    Default: ``None``9596.. py:data:: TRAP_HTTP_EXCEPTIONS9798    If there is no handler for an ``HTTPException``-type exception, re-raise it99    to be handled by the interactive debugger instead of returning it as a100    simple error response.101102    Default: ``False``103104.. py:data:: TRAP_BAD_REQUEST_ERRORS105106    Trying to access a key that doesn't exist from request dicts like ``args``107    and ``form`` will return a 400 Bad Request error page. Enable this to treat108    the error as an unhandled exception instead so that you get the interactive109    debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If110    unset, it is enabled in debug mode.111112    Default: ``None``113114.. py:data:: SECRET_KEY115116    A secret key that will be used for securely signing the session cookie117    and can be used for any other security related needs by extensions or your118    application. It should be a long random ``bytes`` or ``str``. For119    example, copy the output of this to your config::120121        $ python -c 'import secrets; print(secrets.token_hex())'122        '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'123124    **Do not reveal the secret key when posting questions or committing code.**125126    Default: ``None``127128.. py:data:: SECRET_KEY_FALLBACKS129130    A list of old secret keys that can still be used for unsigning. This allows131    a project to implement key rotation without invalidating active sessions or132    other recently-signed secrets.133134    Keys should be removed after an appropriate period of time, as checking each135    additional key adds some overhead.136137    Order should not matter, but the default implementation will test the last138    key in the list first, so it might make sense to order oldest to newest.139140    Flask's built-in secure cookie session supports this. Extensions that use141    :data:`SECRET_KEY` may not support this yet.142143    Default: ``None``144145    .. versionadded:: 3.1146147.. py:data:: SESSION_COOKIE_NAME148149    The name of the session cookie. Can be changed in case you already have a150    cookie with the same name.151152    Default: ``'session'``153154.. py:data:: SESSION_COOKIE_DOMAIN155156    The value of the ``Domain`` parameter on the session cookie. If not set, browsers157    will only send the cookie to the exact domain it was set from. Otherwise, they158    will send it to any subdomain of the given value as well.159160    Not setting this value is more restricted and secure than setting it.161162    Default: ``None``163164    .. warning::165        If this is changed after the browser created a cookie is created with166        one setting, it may result in another being created. Browsers may send167        send both in an undefined order. In that case, you may want to change168        :data:`SESSION_COOKIE_NAME` as well or otherwise invalidate old sessions.169170    .. versionchanged:: 2.3171        Not set by default, does not fall back to ``SERVER_NAME``.172173.. py:data:: SESSION_COOKIE_PATH174175    The path that the session cookie will be valid for. If not set, the cookie176    will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.177178    Default: ``None``179180.. py:data:: SESSION_COOKIE_HTTPONLY181182    Browsers will not allow JavaScript access to cookies marked as "HTTP only"183    for security.184185    Default: ``True``186187.. py:data:: SESSION_COOKIE_SECURE188189    Browsers will only send cookies with requests over HTTPS if the cookie is190    marked "secure". The application must be served over HTTPS for this to make191    sense.192193    Default: ``False``194195.. py:data:: SESSION_COOKIE_PARTITIONED196197    Browsers will send cookies based on the top-level document's domain, rather198    than only the domain of the document setting the cookie. This prevents third199    party cookies set in iframes from "leaking" between separate sites.200201    Browsers are beginning to disallow non-partitioned third party cookies, so202    you need to mark your cookies partitioned if you expect them to work in such203    embedded situations.204205    Enabling this implicitly enables :data:`SESSION_COOKIE_SECURE` as well, as206    it is only valid when served over HTTPS.207208    Default: ``False``209210    .. versionadded:: 3.1211212.. py:data:: SESSION_COOKIE_SAMESITE213214    Restrict how cookies are sent with requests from external sites. Can215    be set to ``'Lax'`` (recommended) or ``'Strict'``.216    See :ref:`security-cookie`.217218    Default: ``None``219220    .. versionadded:: 1.0221222.. py:data:: PERMANENT_SESSION_LIFETIME223224    If ``session.permanent`` is true, the cookie's expiration will be set this225    number of seconds in the future. Can either be a226    :class:`datetime.timedelta` or an ``int``.227228    Flask's default cookie implementation validates that the cryptographic229    signature is not older than this value.230231    Default: ``timedelta(days=31)`` (``2678400`` seconds)232233.. py:data:: SESSION_REFRESH_EACH_REQUEST234235    Control whether the cookie is sent with every response when236    ``session.permanent`` is true. Sending the cookie every time (the default)237    can more reliably keep the session from expiring, but uses more bandwidth.238    Non-permanent sessions are not affected.239240    Default: ``True``241242.. py:data:: USE_X_SENDFILE243244    When serving files, set the ``X-Sendfile`` header instead of serving the245    data with Flask. Some web servers, such as Apache, recognize this and serve246    the data more efficiently. This only makes sense when using such a server.247248    Default: ``False``249250.. py:data:: SEND_FILE_MAX_AGE_DEFAULT251252    When serving files, set the cache control max age to this number of253    seconds. Can be a :class:`datetime.timedelta` or an ``int``.254    Override this value on a per-file basis using255    :meth:`~flask.Flask.get_send_file_max_age` on the application or256    blueprint.257258    If ``None``, ``send_file`` tells the browser to use conditional259    requests will be used instead of a timed cache, which is usually260    preferable.261262    Default: ``None``263264.. py:data:: TRUSTED_HOSTS265266    Validate :attr:`.Request.host` and other attributes that use it against267    these trusted values. Raise a :exc:`~werkzeug.exceptions.SecurityError` if268    the host is invalid, which results in a 400 error. If it is ``None``, all269    hosts are valid. Each value is either an exact match, or can start with270    a dot ``.`` to match any subdomain.271272    Validation is done during routing against this value. ``before_request`` and273    ``after_request`` callbacks will still be called.274275    Default: ``None``276277    .. versionadded:: 3.1278279.. py:data:: SERVER_NAME280281    Inform the application what host and port it is bound to.282283    Must be set if ``subdomain_matching`` is enabled, to be able to extract the284    subdomain from the request.285286    Must be set for ``url_for`` to generate external URLs outside of a287    request context.288289    Default: ``None``290291    .. versionchanged:: 3.1292        Does not restrict requests to only this domain, for both293        ``subdomain_matching`` and ``host_matching``.294295    .. versionchanged:: 1.0296        Does not implicitly enable ``subdomain_matching``.297298    .. versionchanged:: 2.3299        Does not affect ``SESSION_COOKIE_DOMAIN``.300301.. py:data:: APPLICATION_ROOT302303    Inform the application what path it is mounted under by the application /304    web server.  This is used for generating URLs outside the context of a305    request (inside a request, the dispatcher is responsible for setting306    ``SCRIPT_NAME`` instead; see :doc:`/patterns/appdispatch`307    for examples of dispatch configuration).308309    Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not310    set.311312    Default: ``'/'``313314.. py:data:: PREFERRED_URL_SCHEME315316    Use this scheme for generating external URLs when not in a request context.317318    Default: ``'http'``319320.. py:data:: MAX_CONTENT_LENGTH321322    The maximum number of bytes that will be read during this request. If323    this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge`324    error is raised. If it is set to ``None``, no limit is enforced at the325    Flask application level. However, if it is ``None`` and the request has no326    ``Content-Length`` header and the WSGI server does not indicate that it327    terminates the stream, then no data is read to avoid an infinite stream.328329    Each request defaults to this config. It can be set on a specific330    :attr:`.Request.max_content_length` to apply the limit to that specific331    view. This should be set appropriately based on an application's or view's332    specific needs.333334    Default: ``None``335336    .. versionadded:: 0.6337338.. py:data:: MAX_FORM_MEMORY_SIZE339340    The maximum size in bytes any non-file form field may be in a341    ``multipart/form-data`` body. If this limit is exceeded, a 413342    :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it is343    set to ``None``, no limit is enforced at the Flask application level.344345    Each request defaults to this config. It can be set on a specific346    :attr:`.Request.max_form_memory_parts` to apply the limit to that specific347    view. This should be set appropriately based on an application's or view's348    specific needs.349350    Default: ``500_000``351352    .. versionadded:: 3.1353354.. py:data:: MAX_FORM_PARTS355356    The maximum number of fields that may be present in a357    ``multipart/form-data`` body. If this limit is exceeded, a 413358    :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it359    is set to ``None``, no limit is enforced at the Flask application level.360361    Each request defaults to this config. It can be set on a specific362    :attr:`.Request.max_form_parts` to apply the limit to that specific view.363    This should be set appropriately based on an application's or view's364    specific needs.365366    Default: ``1_000``367368    .. versionadded:: 3.1369370.. py:data:: TEMPLATES_AUTO_RELOAD371372    Reload templates when they are changed. If not set, it will be enabled in373    debug mode.374375    Default: ``None``376377.. py:data:: EXPLAIN_TEMPLATE_LOADING378379    Log debugging information tracing how a template file was loaded. This can380    be useful to figure out why a template was not loaded or the wrong file381    appears to be loaded.382383    Default: ``False``384385.. py:data:: MAX_COOKIE_SIZE386387    Warn if cookie headers are larger than this many bytes. Defaults to388    ``4093``. Larger cookies may be silently ignored by browsers. Set to389    ``0`` to disable the warning.390391.. py:data:: PROVIDE_AUTOMATIC_OPTIONS392393    Set to ``False`` to disable the automatic addition of OPTIONS394    responses. This can be overridden per route by altering the395    ``provide_automatic_options`` attribute.396397.. versionadded:: 0.4398   ``LOGGER_NAME``399400.. versionadded:: 0.5401   ``SERVER_NAME``402403.. versionadded:: 0.6404   ``MAX_CONTENT_LENGTH``405406.. versionadded:: 0.7407   ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``408409.. versionadded:: 0.8410   ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,411   ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,412   ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,413   ``SESSION_COOKIE_SECURE``414415.. versionadded:: 0.9416   ``PREFERRED_URL_SCHEME``417418.. versionadded:: 0.10419   ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``420421.. versionadded:: 0.11422   ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,423   ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``424425.. versionchanged:: 1.0426    ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See427    :doc:`/logging` for information about configuration.428429    Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment430    variable.431432    Added :data:`SESSION_COOKIE_SAMESITE` to control the session433    cookie's ``SameSite`` option.434435    Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.436437.. versionchanged:: 2.2438    Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``.439440.. versionchanged:: 2.3441    ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_MIMETYPE``, and442    ``JSONIFY_PRETTYPRINT_REGULAR`` were removed. The default ``app.json`` provider has443    equivalent attributes instead.444445.. versionchanged:: 2.3446    ``ENV`` was removed.447448.. versionadded:: 3.1449    Added :data:`PROVIDE_AUTOMATIC_OPTIONS` to control the default450    addition of autogenerated OPTIONS responses.451452453Configuring from Python Files454-----------------------------455456Configuration becomes more useful if you can store it in a separate file, ideally457located outside the actual application package. You can deploy your application, then458separately configure it for the specific deployment.459460A common pattern is this::461462    app = Flask(__name__)463    app.config.from_object('yourapplication.default_settings')464    app.config.from_envvar('YOURAPPLICATION_SETTINGS')465466This first loads the configuration from the467`yourapplication.default_settings` module and then overrides the values468with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`469environment variable points to.  This environment variable can be set470in the shell before starting the server:471472.. tabs::473474   .. group-tab:: Bash475476      .. code-block:: text477478         $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg479         $ flask run480          * Running on http://127.0.0.1:5000/481482   .. group-tab:: Fish483484      .. code-block:: text485486         $ set -x YOURAPPLICATION_SETTINGS /path/to/settings.cfg487         $ flask run488          * Running on http://127.0.0.1:5000/489490   .. group-tab:: CMD491492      .. code-block:: text493494         > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg495         > flask run496          * Running on http://127.0.0.1:5000/497498   .. group-tab:: Powershell499500      .. code-block:: text501502         > $env:YOURAPPLICATION_SETTINGS = "\path\to\settings.cfg"503         > flask run504          * Running on http://127.0.0.1:5000/505506The configuration files themselves are actual Python files.  Only values507in uppercase are actually stored in the config object later on.  So make508sure to use uppercase letters for your config keys.509510Here is an example of a configuration file::511512    # Example configuration513    SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'514515Make sure to load the configuration very early on, so that extensions have516the ability to access the configuration when starting up.  There are other517methods on the config object as well to load from individual files.  For a518complete reference, read the :class:`~flask.Config` object's519documentation.520521522Configuring from Data Files523---------------------------524525It is also possible to load configuration from a file in a format of526your choice using :meth:`~flask.Config.from_file`. For example to load527from a TOML file:528529.. code-block:: python530531    import tomllib532    app.config.from_file("config.toml", load=tomllib.load, text=False)533534Or from a JSON file:535536.. code-block:: python537538    import json539    app.config.from_file("config.json", load=json.load)540541542Configuring from Environment Variables543--------------------------------------544545In addition to pointing to configuration files using environment546variables, you may find it useful (or necessary) to control your547configuration values directly from the environment. Flask can be548instructed to load all environment variables starting with a specific549prefix into the config using :meth:`~flask.Config.from_prefixed_env`.550551Environment variables can be set in the shell before starting the552server:553554.. tabs::555556   .. group-tab:: Bash557558      .. code-block:: text559560         $ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"561         $ export FLASK_MAIL_ENABLED=false562         $ flask run563          * Running on http://127.0.0.1:5000/564565   .. group-tab:: Fish566567      .. code-block:: text568569         $ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f"570         $ set -x FLASK_MAIL_ENABLED false571         $ flask run572          * Running on http://127.0.0.1:5000/573574   .. group-tab:: CMD575576      .. code-block:: text577578         > set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"579         > set FLASK_MAIL_ENABLED=false580         > flask run581          * Running on http://127.0.0.1:5000/582583   .. group-tab:: Powershell584585      .. code-block:: text586587         > $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f"588         > $env:FLASK_MAIL_ENABLED = "false"589         > flask run590          * Running on http://127.0.0.1:5000/591592The variables can then be loaded and accessed via the config with a key593equal to the environment variable name without the prefix i.e.594595.. code-block:: python596597    app.config.from_prefixed_env()598    app.config["SECRET_KEY"]  # Is "5f352379324c22463451387a0aec5d2f"599600The prefix is ``FLASK_`` by default. This is configurable via the601``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.602603Values will be parsed to attempt to convert them to a more specific type604than strings. By default :func:`json.loads` is used, so any valid JSON605value is possible, including lists and dicts. This is configurable via606the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.607608When adding a boolean value with the default JSON parsing, only "true"609and "false", lowercase, are valid values. Keep in mind that any610non-empty string is considered ``True`` by Python.611612It is possible to set keys in nested dictionaries by separating the613keys with double underscore (``__``). Any intermediate keys that don't614exist on the parent dict will be initialized to an empty dict.615616.. code-block:: text617618    $ export FLASK_MYAPI__credentials__username=user123619620.. code-block:: python621622    app.config["MYAPI"]["credentials"]["username"]  # Is "user123"623624On Windows, environment variable keys are always uppercase, therefore625the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``.626627For even more config loading features, including merging and628case-insensitive Windows support, try a dedicated library such as629Dynaconf_, which includes integration with Flask.630631.. _Dynaconf: https://www.dynaconf.com/632633634Configuration Best Practices635----------------------------636637The downside with the approach mentioned earlier is that it makes testing638a little harder.  There is no single 100% solution for this problem in639general, but there are a couple of things you can keep in mind to improve640that experience:6416421.  Create your application in a function and register blueprints on it.643    That way you can create multiple instances of your application with644    different configurations attached which makes unit testing a lot645    easier.  You can use this to pass in configuration as needed.6466472.  Do not write code that needs the configuration at import time.  If you648    limit yourself to request-only accesses to the configuration you can649    reconfigure the object later on as needed.6506513.  Make sure to load the configuration very early on, so that652    extensions can access the configuration when calling ``init_app``.653654655.. _config-dev-prod:656657Development / Production658------------------------659660Most applications need more than one configuration.  There should be at661least separate configurations for the production server and the one used662during development.  The easiest way to handle this is to use a default663configuration that is always loaded and part of the version control, and a664separate configuration that overrides the values as necessary as mentioned665in the example above::666667    app = Flask(__name__)668    app.config.from_object('yourapplication.default_settings')669    app.config.from_envvar('YOURAPPLICATION_SETTINGS')670671Then you just have to add a separate :file:`config.py` file and export672``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done.  However673there are alternative ways as well.  For example you could use imports or674subclassing.675676What is very popular in the Django world is to make the import explicit in677the config file by adding ``from yourapplication.default_settings678import *`` to the top of the file and then overriding the changes by hand.679You could also inspect an environment variable like680``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc681and import different hard-coded files based on that.682683An interesting pattern is also to use classes and inheritance for684configuration::685686    class Config(object):687        TESTING = False688689    class ProductionConfig(Config):690        DATABASE_URI = 'mysql://user@localhost/foo'691692    class DevelopmentConfig(Config):693        DATABASE_URI = "sqlite:////tmp/foo.db"694695    class TestingConfig(Config):696        DATABASE_URI = 'sqlite:///:memory:'697        TESTING = True698699To enable such a config you just have to call into700:meth:`~flask.Config.from_object`::701702    app.config.from_object('configmodule.ProductionConfig')703704Note that :meth:`~flask.Config.from_object` does not instantiate the class705object. If you need to instantiate the class, such as to access a property,706then you must do so before calling :meth:`~flask.Config.from_object`::707708    from configmodule import ProductionConfig709    app.config.from_object(ProductionConfig())710711    # Alternatively, import via string:712    from werkzeug.utils import import_string713    cfg = import_string('configmodule.ProductionConfig')()714    app.config.from_object(cfg)715716Instantiating the configuration object allows you to use ``@property`` in717your configuration classes::718719    class Config(object):720        """Base config, uses staging database server."""721        TESTING = False722        DB_SERVER = '192.168.1.56'723724        @property725        def DATABASE_URI(self):  # Note: all caps726            return f"mysql://user@{self.DB_SERVER}/foo"727728    class ProductionConfig(Config):729        """Uses production database server."""730        DB_SERVER = '192.168.19.32'731732    class DevelopmentConfig(Config):733        DB_SERVER = 'localhost'734735    class TestingConfig(Config):736        DB_SERVER = 'localhost'737        DATABASE_URI = 'sqlite:///:memory:'738739There are many different ways and it's up to you how you want to manage740your configuration files.  However here a list of good recommendations:741742-   Keep a default configuration in version control.  Either populate the743    config with this default configuration or import it in your own744    configuration files before overriding values.745-   Use an environment variable to switch between the configurations.746    This can be done from outside the Python interpreter and makes747    development and deployment much easier because you can quickly and748    easily switch between different configs without having to touch the749    code at all.  If you are working often on different projects you can750    even create your own script for sourcing that activates a virtualenv751    and exports the development configuration for you.752-   Use a tool like `fabric`_ to push code and configuration separately753    to the production server(s).754755.. _fabric: https://www.fabfile.org/756757758.. _instance-folders:759760Instance Folders761----------------762763.. versionadded:: 0.8764765Flask 0.8 introduces instance folders.  Flask for a long time made it766possible to refer to paths relative to the application's folder directly767(via :attr:`Flask.root_path`).  This was also how many developers loaded768configurations stored next to the application.  Unfortunately however this769only works well if applications are not packages in which case the root770path refers to the contents of the package.771772With Flask 0.8 a new attribute was introduced:773:attr:`Flask.instance_path`.  It refers to a new concept called the774“instance folder”.  The instance folder is designed to not be under775version control and be deployment specific.  It's the perfect place to776drop things that either change at runtime or configuration files.777778You can either explicitly provide the path of the instance folder when779creating the Flask application or you can let Flask autodetect the780instance folder.  For explicit configuration use the `instance_path`781parameter::782783    app = Flask(__name__, instance_path='/path/to/instance/folder')784785Please keep in mind that this path *must* be absolute when provided.786787If the `instance_path` parameter is not provided the following default788locations are used:789790-   Uninstalled module::791792        /myapp.py793        /instance794795-   Uninstalled package::796797        /myapp798            /__init__.py799        /instance800801-   Installed module or package::802803        $PREFIX/lib/pythonX.Y/site-packages/myapp804        $PREFIX/var/myapp-instance805806    ``$PREFIX`` is the prefix of your Python installation.  This can be807    ``/usr`` or the path to your virtualenv.  You can print the value of808    ``sys.prefix`` to see what the prefix is set to.809810Since the config object provided loading of configuration files from811relative filenames we made it possible to change the loading via filenames812to be relative to the instance path if wanted.  The behavior of relative813paths in config files can be flipped between “relative to the application814root” (the default) to “relative to instance folder” via the815`instance_relative_config` switch to the application constructor::816817    app = Flask(__name__, instance_relative_config=True)818819Here is a full example of how to configure Flask to preload the config820from a module and then override the config from a file in the instance821folder if it exists::822823    app = Flask(__name__, instance_relative_config=True)824    app.config.from_object('yourapplication.default_settings')825    app.config.from_pyfile('application.cfg', silent=True)826827The path to the instance folder can be found via the828:attr:`Flask.instance_path`.  Flask also provides a shortcut to open a829file from the instance folder with :meth:`Flask.open_instance_resource`.830831Example usage for both::832833    filename = os.path.join(app.instance_path, 'application.cfg')834    with open(filename) as f:835        config = f.read()836837    # or via open_instance_resource:838    with app.open_instance_resource('application.cfg') as f:839        config = f.read()