config.rst
This file
Path
docs/config.rst
721 lines · 23.8 KiB
Last changed by
Merge branch '2.3.x'David Lordbefore adoption31fd9c8
History of this fileTake it
The walk stopped after 200 commits: lines older than 93a7f08 point at it.
pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 1–44why, one step back1Configuration 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 )4344Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 45–46why, one step back45Debug Mode46----------pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 47why, one step back47Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 48–49why, one step back48The :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 theMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 50–51why, one step back50``--debug`` option on the ``flask`` or ``flask run`` command. ``flask run`` will use the51interactive debugger and reloader by default in debug mode.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 52why, one step back52Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
line 53why, one step back53.. code-block:: textpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 54why, one step back54new run debug docsDavid Lordbefore adoption74e5263
line 55why, one step back55 $ flask --app hello run --debugpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 56why, one step back56Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 57why, one step back57Using the option is recommended. While it is possible to set :data:`DEBUG` in yourMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 58–60why, one step back58config 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.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 61–69why, one step back616263Builtin Configuration Values64----------------------------6566The following configuration values are used internally by Flask:6768.. py:data:: DEBUG69Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 70–74why, one step back70 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.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 75–77why, one step back7576 **Do not enable debug mode when deploying in production.**77Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 78why, one step back78 Default: ``False``pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 79–136why, one step back7980.. py:data:: TESTING8182 Enable testing mode. Exceptions are propagated rather than handled by the83 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:: SESSION_COOKIE_NAME129130 The name of the session cookie. Can be changed in case you already have a131 cookie with the same name.132133 Default: ``'session'``134135.. py:data:: SESSION_COOKIE_DOMAIN136Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 137–139why, one step back137 The value of the ``Domain`` parameter on the session cookie. If not set, browsers138 will only send the cookie to the exact domain it was set from. Otherwise, they139 will send it to any subdomain of the given value as well.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 140why, one step back140Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 141–142why, one step back141 Not setting this value is more restricted and secure than setting it.142pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 143–144why, one step back143 Default: ``None``144Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 145–147why, one step back145 .. versionchanged:: 2.3146 Not set by default, does not fall back to ``SERVER_NAME``.147pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 148–230why, one step back148.. py:data:: SESSION_COOKIE_PATH149150 The path that the session cookie will be valid for. If not set, the cookie151 will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.152153 Default: ``None``154155.. py:data:: SESSION_COOKIE_HTTPONLY156157 Browsers will not allow JavaScript access to cookies marked as "HTTP only"158 for security.159160 Default: ``True``161162.. py:data:: SESSION_COOKIE_SECURE163164 Browsers will only send cookies with requests over HTTPS if the cookie is165 marked "secure". The application must be served over HTTPS for this to make166 sense.167168 Default: ``False``169170.. py:data:: SESSION_COOKIE_SAMESITE171172 Restrict how cookies are sent with requests from external sites. Can173 be set to ``'Lax'`` (recommended) or ``'Strict'``.174 See :ref:`security-cookie`.175176 Default: ``None``177178 .. versionadded:: 1.0179180.. py:data:: PERMANENT_SESSION_LIFETIME181182 If ``session.permanent`` is true, the cookie's expiration will be set this183 number of seconds in the future. Can either be a184 :class:`datetime.timedelta` or an ``int``.185186 Flask's default cookie implementation validates that the cryptographic187 signature is not older than this value.188189 Default: ``timedelta(days=31)`` (``2678400`` seconds)190191.. py:data:: SESSION_REFRESH_EACH_REQUEST192193 Control whether the cookie is sent with every response when194 ``session.permanent`` is true. Sending the cookie every time (the default)195 can more reliably keep the session from expiring, but uses more bandwidth.196 Non-permanent sessions are not affected.197198 Default: ``True``199200.. py:data:: USE_X_SENDFILE201202 When serving files, set the ``X-Sendfile`` header instead of serving the203 data with Flask. Some web servers, such as Apache, recognize this and serve204 the data more efficiently. This only makes sense when using such a server.205206 Default: ``False``207208.. py:data:: SEND_FILE_MAX_AGE_DEFAULT209210 When serving files, set the cache control max age to this number of211 seconds. Can be a :class:`datetime.timedelta` or an ``int``.212 Override this value on a per-file basis using213 :meth:`~flask.Flask.get_send_file_max_age` on the application or214 blueprint.215216 If ``None``, ``send_file`` tells the browser to use conditional217 requests will be used instead of a timed cache, which is usually218 preferable.219220 Default: ``None``221222.. py:data:: SERVER_NAME223224 Inform the application what host and port it is bound to. Required225 for subdomain route matching support.226227 If set, ``url_for`` can generate external URLs with only an application228 context instead of a request context.229230 Default: ``None``Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 231–233why, one step back231232 .. versionchanged:: 2.3233 Does not affect ``SESSION_COOKIE_DOMAIN``.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 234–321why, one step back234235.. py:data:: APPLICATION_ROOT236237 Inform the application what path it is mounted under by the application /238 web server. This is used for generating URLs outside the context of a239 request (inside a request, the dispatcher is responsible for setting240 ``SCRIPT_NAME`` instead; see :doc:`/patterns/appdispatch`241 for examples of dispatch configuration).242243 Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not244 set.245246 Default: ``'/'``247248.. py:data:: PREFERRED_URL_SCHEME249250 Use this scheme for generating external URLs when not in a request context.251252 Default: ``'http'``253254.. py:data:: MAX_CONTENT_LENGTH255256 Don't read more than this many bytes from the incoming request data. If not257 set and the request does not specify a ``CONTENT_LENGTH``, no data will be258 read for security.259260 Default: ``None``261262.. py:data:: TEMPLATES_AUTO_RELOAD263264 Reload templates when they are changed. If not set, it will be enabled in265 debug mode.266267 Default: ``None``268269.. py:data:: EXPLAIN_TEMPLATE_LOADING270271 Log debugging information tracing how a template file was loaded. This can272 be useful to figure out why a template was not loaded or the wrong file273 appears to be loaded.274275 Default: ``False``276277.. py:data:: MAX_COOKIE_SIZE278279 Warn if cookie headers are larger than this many bytes. Defaults to280 ``4093``. Larger cookies may be silently ignored by browsers. Set to281 ``0`` to disable the warning.282283.. versionadded:: 0.4284 ``LOGGER_NAME``285286.. versionadded:: 0.5287 ``SERVER_NAME``288289.. versionadded:: 0.6290 ``MAX_CONTENT_LENGTH``291292.. versionadded:: 0.7293 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``294295.. versionadded:: 0.8296 ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,297 ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,298 ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,299 ``SESSION_COOKIE_SECURE``300301.. versionadded:: 0.9302 ``PREFERRED_URL_SCHEME``303304.. versionadded:: 0.10305 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``306307.. versionadded:: 0.11308 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,309 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``310311.. versionchanged:: 1.0312 ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See313 :doc:`/logging` for information about configuration.314315 Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment316 variable.317318 Added :data:`SESSION_COOKIE_SAMESITE` to control the session319 cookie's ``SameSite`` option.320321 Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.Merge pull request #4666 from pallets/debug-contextDavid Lordbefore adoption6916697
lines 322–324why, one step back322323.. versionchanged:: 2.2324 Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``.Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
line 325why, one step back325Merge pull request #4995 from pallets/remove-deprecatedDavid Lordbefore adoption1ee22e1
lines 326–328why, one step back326.. versionchanged:: 2.3327 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_MIMETYPE``, and328 ``JSONIFY_PRETTYPRINT_REGULAR`` were removed. The default ``app.json`` provider hasMerge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
line 329why, one step back329 equivalent attributes instead.Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 330why, one step back330Merge pull request #4995 from pallets/remove-deprecatedDavid Lordbefore adoption1ee22e1
lines 331–332why, one step back331.. versionchanged:: 2.3332 ``ENV`` was removed.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 333–337why, one step back333334335Configuring from Python Files336-----------------------------337Merge branch '2.2.x'David Lordbefore adoption87584e8
lines 338–340why, one step back338Configuration becomes more useful if you can store it in a separate file, ideally339located outside the actual application package. You can deploy your application, then340separately configure it for the specific deployment.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 341why, one step back341Merge branch '2.2.x'David Lordbefore adoption87584e8
line 342why, one step back342A common pattern is this::pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 343–363why, one step back343344 app = Flask(__name__)345 app.config.from_object('yourapplication.default_settings')346 app.config.from_envvar('YOURAPPLICATION_SETTINGS')347348This first loads the configuration from the349`yourapplication.default_settings` module and then overrides the values350with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`351environment variable points to. This environment variable can be set352in the shell before starting the server:353354.. tabs::355356 .. group-tab:: Bash357358 .. code-block:: text359360 $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg361 $ flask run362 * Running on http://127.0.0.1:5000/363Merge branch '2.0.x'David Lordbefore adoptione37e871
lines 364–371why, one step back364 .. group-tab:: Fish365366 .. code-block:: text367368 $ set -x YOURAPPLICATION_SETTINGS /path/to/settings.cfg369 $ flask run370 * Running on http://127.0.0.1:5000/371pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 372–412why, one step back372 .. group-tab:: CMD373374 .. code-block:: text375376 > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg377 > flask run378 * Running on http://127.0.0.1:5000/379380 .. group-tab:: Powershell381382 .. code-block:: text383384 > $env:YOURAPPLICATION_SETTINGS = "\path\to\settings.cfg"385 > flask run386 * Running on http://127.0.0.1:5000/387388The configuration files themselves are actual Python files. Only values389in uppercase are actually stored in the config object later on. So make390sure to use uppercase letters for your config keys.391392Here is an example of a configuration file::393394 # Example configuration395 SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'396397Make sure to load the configuration very early on, so that extensions have398the ability to access the configuration when starting up. There are other399methods on the config object as well to load from individual files. For a400complete reference, read the :class:`~flask.Config` object's401documentation.402403404Configuring from Data Files405---------------------------406407It is also possible to load configuration from a file in a format of408your choice using :meth:`~flask.Config.from_file`. For example to load409from a TOML file:410411.. code-block:: python412Merge branch '2.3.x'David Lordbefore adoption31fd9c8
lines 413–414why, one step back413 import tomllib414 app.config.from_file("config.toml", load=tomllib.load, text=False)pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 415–426why, one step back415416Or from a JSON file:417418.. code-block:: python419420 import json421 app.config.from_file("config.json", load=json.load)422423424Configuring from Environment Variables425--------------------------------------426Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 427–431why, one step back427In addition to pointing to configuration files using environment428variables, you may find it useful (or necessary) to control your429configuration values directly from the environment. Flask can be430instructed to load all environment variables starting with a specific431prefix into the config using :meth:`~flask.Config.from_prefixed_env`.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 432why, one step back432Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 433–434why, one step back433Environment variables can be set in the shell before starting the434server:pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 435–441why, one step back435436.. tabs::437438 .. group-tab:: Bash439440 .. code-block:: text441Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 442–443why, one step back442 $ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"443 $ export FLASK_MAIL_ENABLED=falseMerge branch '2.0.x'David Lordbefore adoptione37e871
lines 444–450why, one step back444 $ flask run445 * Running on http://127.0.0.1:5000/446447 .. group-tab:: Fish448449 .. code-block:: text450Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 451–452why, one step back451 $ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f"452 $ set -x FLASK_MAIL_ENABLED falsepin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 453–459why, one step back453 $ flask run454 * Running on http://127.0.0.1:5000/455456 .. group-tab:: CMD457458 .. code-block:: text459Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 460–461why, one step back460 > set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"461 > set FLASK_MAIL_ENABLED=falsepin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 462–468why, one step back462 > flask run463 * Running on http://127.0.0.1:5000/464465 .. group-tab:: Powershell466467 .. code-block:: text468Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 469–470why, one step back469 > $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f"470 > $env:FLASK_MAIL_ENABLED = "false"pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 471–473why, one step back471 > flask run472 * Running on http://127.0.0.1:5000/473Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 474–475why, one step back474The variables can then be loaded and accessed via the config with a key475equal to the environment variable name without the prefix i.e.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 476why, one step back476Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
line 477why, one step back477.. code-block:: pythonpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 478why, one step back478Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 479–480why, one step back479 app.config.from_prefixed_env()480 app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f"pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 481why, one step back481Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 482–483why, one step back482The prefix is ``FLASK_`` by default. This is configurable via the483``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 484why, one step back484Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 485–488why, one step back485Values will be parsed to attempt to convert them to a more specific type486than strings. By default :func:`json.loads` is used, so any valid JSON487value is possible, including lists and dicts. This is configurable via488the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 489why, one step back489Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 490–492why, one step back490When adding a boolean value with the default JSON parsing, only "true"491and "false", lowercase, are valid values. Keep in mind that any492non-empty string is considered ``True`` by Python.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 493why, one step back493Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 494–496why, one step back494It is possible to set keys in nested dictionaries by separating the495keys with double underscore (``__``). Any intermediate keys that don't496exist on the parent dict will be initialized to an empty dict.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 497why, one step back497Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
line 498why, one step back498.. code-block:: textpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 499why, one step back499Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
line 500why, one step back500 $ export FLASK_MYAPI__credentials__username=user123pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 501why, one step back501Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
line 502why, one step back502.. code-block:: pythonpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 503why, one step back503Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 504–515why, one step back504 app.config["MYAPI"]["credentials"]["username"] # Is "user123"505506On Windows, environment variable keys are always uppercase, therefore507the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``.508509For even more config loading features, including merging and510case-insensitive Windows support, try a dedicated library such as511Dynaconf_, which includes integration with Flask.512513.. _Dynaconf: https://www.dynaconf.com/514515pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 516–531why, one step back516Configuration Best Practices517----------------------------518519The downside with the approach mentioned earlier is that it makes testing520a little harder. There is no single 100% solution for this problem in521general, but there are a couple of things you can keep in mind to improve522that experience:5235241. Create your application in a function and register blueprints on it.525 That way you can create multiple instances of your application with526 different configurations attached which makes unit testing a lot527 easier. You can use this to pass in configuration as needed.5285292. Do not write code that needs the configuration at import time. If you530 limit yourself to request-only accesses to the configuration you can531 reconfigure the object later on as needed.Merge pull request #4479 from pgjones/env_configDavid Lordbefore adoption2f5a2ab
lines 532–535why, one step back5325333. Make sure to load the configuration very early on, so that534 extensions can access the configuration when calling ``init_app``.535pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 536–633why, one step back536537.. _config-dev-prod:538539Development / Production540------------------------541542Most applications need more than one configuration. There should be at543least separate configurations for the production server and the one used544during development. The easiest way to handle this is to use a default545configuration that is always loaded and part of the version control, and a546separate configuration that overrides the values as necessary as mentioned547in the example above::548549 app = Flask(__name__)550 app.config.from_object('yourapplication.default_settings')551 app.config.from_envvar('YOURAPPLICATION_SETTINGS')552553Then you just have to add a separate :file:`config.py` file and export554``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However555there are alternative ways as well. For example you could use imports or556subclassing.557558What is very popular in the Django world is to make the import explicit in559the config file by adding ``from yourapplication.default_settings560import *`` to the top of the file and then overriding the changes by hand.561You could also inspect an environment variable like562``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc563and import different hard-coded files based on that.564565An interesting pattern is also to use classes and inheritance for566configuration::567568 class Config(object):569 TESTING = False570571 class ProductionConfig(Config):572 DATABASE_URI = 'mysql://user@localhost/foo'573574 class DevelopmentConfig(Config):575 DATABASE_URI = "sqlite:////tmp/foo.db"576577 class TestingConfig(Config):578 DATABASE_URI = 'sqlite:///:memory:'579 TESTING = True580581To enable such a config you just have to call into582:meth:`~flask.Config.from_object`::583584 app.config.from_object('configmodule.ProductionConfig')585586Note that :meth:`~flask.Config.from_object` does not instantiate the class587object. If you need to instantiate the class, such as to access a property,588then you must do so before calling :meth:`~flask.Config.from_object`::589590 from configmodule import ProductionConfig591 app.config.from_object(ProductionConfig())592593 # Alternatively, import via string:594 from werkzeug.utils import import_string595 cfg = import_string('configmodule.ProductionConfig')()596 app.config.from_object(cfg)597598Instantiating the configuration object allows you to use ``@property`` in599your configuration classes::600601 class Config(object):602 """Base config, uses staging database server."""603 TESTING = False604 DB_SERVER = '192.168.1.56'605606 @property607 def DATABASE_URI(self): # Note: all caps608 return f"mysql://user@{self.DB_SERVER}/foo"609610 class ProductionConfig(Config):611 """Uses production database server."""612 DB_SERVER = '192.168.19.32'613614 class DevelopmentConfig(Config):615 DB_SERVER = 'localhost'616617 class TestingConfig(Config):618 DB_SERVER = 'localhost'619 DATABASE_URI = 'sqlite:///:memory:'620621There are many different ways and it's up to you how you want to manage622your configuration files. However here a list of good recommendations:623624- Keep a default configuration in version control. Either populate the625 config with this default configuration or import it in your own626 configuration files before overriding values.627- Use an environment variable to switch between the configurations.628 This can be done from outside the Python interpreter and makes629 development and deployment much easier because you can quickly and630 easily switch between different configs without having to touch the631 code at all. If you are working often on different projects you can632 even create your own script for sourcing that activates a virtualenv633 and exports the development configuration for you.Merge branch '2.2.x'David Lordbefore adoption87584e8
lines 634–635why, one step back634- Use a tool like `fabric`_ to push code and configuration separately635 to the production server(s).pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 636–721why, one step back636637.. _fabric: https://www.fabfile.org/638639640.. _instance-folders:641642Instance Folders643----------------644645.. versionadded:: 0.8646647Flask 0.8 introduces instance folders. Flask for a long time made it648possible to refer to paths relative to the application's folder directly649(via :attr:`Flask.root_path`). This was also how many developers loaded650configurations stored next to the application. Unfortunately however this651only works well if applications are not packages in which case the root652path refers to the contents of the package.653654With Flask 0.8 a new attribute was introduced:655:attr:`Flask.instance_path`. It refers to a new concept called the656“instance folder”. The instance folder is designed to not be under657version control and be deployment specific. It's the perfect place to658drop things that either change at runtime or configuration files.659660You can either explicitly provide the path of the instance folder when661creating the Flask application or you can let Flask autodetect the662instance folder. For explicit configuration use the `instance_path`663parameter::664665 app = Flask(__name__, instance_path='/path/to/instance/folder')666667Please keep in mind that this path *must* be absolute when provided.668669If the `instance_path` parameter is not provided the following default670locations are used:671672- Uninstalled module::673674 /myapp.py675 /instance676677- Uninstalled package::678679 /myapp680 /__init__.py681 /instance682683- Installed module or package::684685 $PREFIX/lib/pythonX.Y/site-packages/myapp686 $PREFIX/var/myapp-instance687688 ``$PREFIX`` is the prefix of your Python installation. This can be689 ``/usr`` or the path to your virtualenv. You can print the value of690 ``sys.prefix`` to see what the prefix is set to.691692Since the config object provided loading of configuration files from693relative filenames we made it possible to change the loading via filenames694to be relative to the instance path if wanted. The behavior of relative695paths in config files can be flipped between “relative to the application696root” (the default) to “relative to instance folder” via the697`instance_relative_config` switch to the application constructor::698699 app = Flask(__name__, instance_relative_config=True)700701Here is a full example of how to configure Flask to preload the config702from a module and then override the config from a file in the instance703folder if it exists::704705 app = Flask(__name__, instance_relative_config=True)706 app.config.from_object('yourapplication.default_settings')707 app.config.from_pyfile('application.cfg', silent=True)708709The path to the instance folder can be found via the710:attr:`Flask.instance_path`. Flask also provides a shortcut to open a711file from the instance folder with :meth:`Flask.open_instance_resource`.712713Example usage for both::714715 filename = os.path.join(app.instance_path, 'application.cfg')716 with open(filename) as f:717 config = f.read()718719 # or via open_instance_resource:720 with app.open_instance_resource('application.cfg') as f:721 config = f.read()