Skip to content
Myr

config.rst

This file

Path

docs/config.rst

694 lines · 23.7 KiB

Last changed by

Merge branch '1.0.x'David Lordbefore adoption2236ba9

History of this file

Take it

The walk stopped after 200 commits: lines older than 49f3e96 point at it.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 1–11why, one step back
1.. _config:
23Configuration Handling4======================56Applications need some kind of configuration. There are different settings7you might want to change depending on the application environment like8toggling the debug mode, setting the secret key, and other such9environment-specific things.1011The way Flask is designed usually requires the configuration to be

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 12why, one step back
12available when the application starts up. You can hard code the

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 13–22why, one step back
13configuration in the code, which for many small applications is not
14actually that bad, but there are better ways.1516Independent of how you load your config, there is a config object17available which holds the loaded configuration values:18The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`19object. This is the place where Flask itself puts certain configuration20values and also where extensions can put their configuration values. But21this is also where you can have your own configuration.22

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 23why, one step back
23

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 24–30why, one step back
24Configuration Basics
25--------------------2627The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and28can be modified just like any dictionary::2930 app = Flask(__name__)

Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522

line 31why, one step back
31 app.config['TESTING'] = True

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 32–35why, one step back
32
33Certain configuration values are also forwarded to the34:attr:`~flask.Flask` object so you can read and write them from there::35

Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522

line 36why, one step back
36 app.testing = True

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 37–41why, one step back
37
38To update multiple keys at once you can use the :meth:`dict.update`39method::4041 app.config.update(

Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522

line 42why, one step back
42 TESTING=True,

Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d

line 43why, one step back
43 SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/'

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 44–45why, one step back
44 )
45

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 46why, one step back
46

Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522

lines 47–48why, one step back
47Environment and Debug Features
48------------------------------

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 49why, one step back
49

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 50–53why, one step back
50The :data:`ENV` and :data:`DEBUG` config values are special because they
51may behave inconsistently if changed after the app has begun setting up.52In order to set the environment and debug mode reliably, Flask uses53environment variables.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 54why, one step back
54

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 55–58why, one step back
55The environment is used to indicate to Flask, extensions, and other
56programs, like Sentry, what context Flask is running in. It is57controlled with the :envvar:`FLASK_ENV` environment variable and58defaults to ``production``.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 59why, one step back
59

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 60–63why, one step back
60Setting :envvar:`FLASK_ENV` to ``development`` will enable debug mode.
61``flask run`` will use the interactive debugger and reloader by default62in debug mode. To control this separately from the environment, use the63:envvar:`FLASK_DEBUG` flag.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 64why, one step back
64

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 65–67why, one step back
65.. versionchanged:: 1.0
66 Added :envvar:`FLASK_ENV` to control the environment separately67 from debug mode. The development environment enables debug mode.

Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522

line 68why, one step back
68

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 69–70why, one step back
69To switch Flask to the development environment and enable debug mode,
70set :envvar:`FLASK_ENV`::

Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522

line 71why, one step back
71

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 72–73why, one step back
72 $ export FLASK_ENV=development
73 $ flask run

Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522

line 74why, one step back
74

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 75why, one step back
75(On Windows, use ``set`` instead of ``export``.)

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 76why, one step back
76

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 77–83why, one step back
77Using the environment variables as described above is recommended. While
78it is possible to set :data:`ENV` and :data:`DEBUG` in your config or79code, this is strongly discouraged. They can't be read early by the80``flask`` command, and some systems or extensions may have already81configured themselves based on a previous value.8283

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 84–88why, one step back
84Builtin Configuration Values
85----------------------------8687The following configuration values are used internally by Flask:88

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 89–102why, one step back
89.. py:data:: ENV
9091 What environment the app is running in. Flask and extensions may92 enable behaviors based on the environment, such as enabling debug93 mode. The :attr:`~flask.Flask.env` attribute maps to this config94 key. This is set by the :envvar:`FLASK_ENV` environment variable and95 may not behave as expected if set in code.9697 **Do not enable development when deploying in production.**9899 Default: ``'production'``100101 .. versionadded:: 1.0102

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 103–104why, one step back
103.. py:data:: DEBUG
104

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 105–111why, one step back
105 Whether debug mode is enabled. When using ``flask run`` to start the
106 development server, an interactive debugger will be shown for107 unhandled exceptions, and the server will be reloaded when code108 changes. The :attr:`~flask.Flask.debug` attribute maps to this109 config key. This is enabled when :data:`ENV` is ``'development'``110 and is overridden by the ``FLASK_DEBUG`` environment variable. It111 may not behave as expected if set in code.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 112why, one step back
112

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 113why, one step back
113 **Do not enable debug mode when deploying in production.**

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 114why, one step back
114

Merge pull request #2733 from kivS/patch-1Hsiaoming Yangbefore adoptionea316d2

line 115why, one step back
115 Default: ``True`` if :data:`ENV` is ``'development'``, or ``False``

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 116why, one step back
116 otherwise.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 117–149why, one step back
117
118.. py:data:: TESTING119120 Enable testing mode. Exceptions are propagated rather than handled by the121 the app's error handlers. Extensions may also change their behavior to122 facilitate easier testing. You should enable this in your own tests.123124 Default: ``False``125126.. py:data:: PROPAGATE_EXCEPTIONS127128 Exceptions are re-raised rather than being handled by the app's error129 handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG``130 is enabled.131132 Default: ``None``133134.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION135136 Don't pop the request context when an exception occurs. If not set, this137 is true if ``DEBUG`` is true. This allows debuggers to introspect the138 request data on errors, and should normally not need to be set directly.139140 Default: ``None``141142.. py:data:: TRAP_HTTP_EXCEPTIONS143144 If there is no handler for an ``HTTPException``-type exception, re-raise it145 to be handled by the interactive debugger instead of returning it as a146 simple error response.147148 Default: ``False``149

Merge pull request #2552 from greyli/patch-6Hsiaoming Yangbefore adoption4c9bf6e

line 150why, one step back
150.. py:data:: TRAP_BAD_REQUEST_ERRORS

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 151–166why, one step back
151
152 Trying to access a key that doesn't exist from request dicts like ``args``153 and ``form`` will return a 400 Bad Request error page. Enable this to treat154 the error as an unhandled exception instead so that you get the interactive155 debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If156 unset, it is enabled in debug mode.157158 Default: ``None``159160.. py:data:: SECRET_KEY161162 A secret key that will be used for securely signing the session cookie163 and can be used for any other security related needs by extensions or your164 application. It should be a long random string of bytes, although unicode165 is accepted too. For example, copy the output of this to your config::166

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 167why, one step back
167 $ python -c 'import os; print(os.urandom(16))'

one more secret key in docsDavid Lordbefore adoption01e2d80

line 168why, one step back
168 b'_5#y2L"F4Q8z\n\xec]/'

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 169–183why, one step back
169
170 **Do not reveal the secret key when posting questions or committing code.**171172 Default: ``None``173174.. py:data:: SESSION_COOKIE_NAME175176 The name of the session cookie. Can be changed in case you already have a177 cookie with the same name.178179 Default: ``'session'``180181.. py:data:: SESSION_COOKIE_DOMAIN182183 The domain match rule that the session cookie will be valid for. If not

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 184–185why, one step back
184 set, the cookie will be valid for all subdomains of :data:`SERVER_NAME`.
185 If ``False``, the cookie's domain will not be set.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 186–210why, one step back
186
187 Default: ``None``188189.. py:data:: SESSION_COOKIE_PATH190191 The path that the session cookie will be valid for. If not set, the cookie192 will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.193194 Default: ``None``195196.. py:data:: SESSION_COOKIE_HTTPONLY197198 Browsers will not allow JavaScript access to cookies marked as "HTTP only"199 for security.200201 Default: ``True``202203.. py:data:: SESSION_COOKIE_SECURE204205 Browsers will only send cookies with requests over HTTPS if the cookie is206 marked "secure". The application must be served over HTTPS for this to make207 sense.208209 Default: ``False``210

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

lines 211–220why, one step back
211.. py:data:: SESSION_COOKIE_SAMESITE
212213 Restrict how cookies are sent with requests from external sites. Can214 be set to ``'Lax'`` (recommended) or ``'Strict'``.215 See :ref:`security-cookie`.216217 Default: ``None``218219 .. versionadded:: 1.0220

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 221–222why, one step back
221.. py:data:: PERMANENT_SESSION_LIFETIME
222

mention that session signature checks max ageDavid Lordbefore adoption2efb565

lines 223–228why, one step back
223 If ``session.permanent`` is true, the cookie's expiration will be set this
224 number of seconds in the future. Can either be a225 :class:`datetime.timedelta` or an ``int``.226227 Flask's default cookie implementation validates that the cryptographic228 signature is not older than this value.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 229–259why, one step back
229
230 Default: ``timedelta(days=31)`` (``2678400`` seconds)231232.. py:data:: SESSION_REFRESH_EACH_REQUEST233234 Control whether the cookie is sent with every response when235 ``session.permanent`` is true. Sending the cookie every time (the default)236 can more reliably keep the session from expiring, but uses more bandwidth.237 Non-permanent sessions are not affected.238239 Default: ``True``240241.. py:data:: USE_X_SENDFILE242243 When serving files, set the ``X-Sendfile`` header instead of serving the244 data with Flask. Some web servers, such as Apache, recognize this and serve245 the data more efficiently. This only makes sense when using such a server.246247 Default: ``False``248249.. py:data:: SEND_FILE_MAX_AGE_DEFAULT250251 When serving files, set the cache control max age to this number of252 seconds. Can either be a :class:`datetime.timedelta` or an ``int``.253 Override this value on a per-file basis using254 :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint.255256 Default: ``timedelta(hours=12)`` (``43200`` seconds)257258.. py:data:: SERVER_NAME259

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 260–261why, one step back
260 Inform the application what host and port it is bound to. Required
261 for subdomain route matching support.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 262–263why, one step back
262
263 If set, will be used for the session cookie domain if

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 264–267why, one step back
264 :data:`SESSION_COOKIE_DOMAIN` is not set. Modern web browsers will
265 not allow setting cookies for domains without a dot. To use a domain266 locally, add any names that should route to the app to your267 ``hosts`` file. ::

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 268–303why, one step back
268
269 127.0.0.1 localhost.dev270271 If set, ``url_for`` can generate external URLs with only an application272 context instead of a request context.273274 Default: ``None``275276.. py:data:: APPLICATION_ROOT277278 Inform the application what path it is mounted under by the application /279 web server.280281 Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not282 set.283284 Default: ``'/'``285286.. py:data:: PREFERRED_URL_SCHEME287288 Use this scheme for generating external URLs when not in a request context.289290 Default: ``'http'``291292.. py:data:: MAX_CONTENT_LENGTH293294 Don't read more than this many bytes from the incoming request data. If not295 set and the request does not specify a ``CONTENT_LENGTH``, no data will be296 read for security.297298 Default: ``None``299300.. py:data:: JSON_AS_ASCII301302 Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON303 will be returned as a Unicode string, or encoded as ``UTF-8`` by

Merge branch '1.0-maintenance'David Lordbefore adoptionac6746d

lines 304–305why, one step back
304 ``jsonify``. This has security implications when rendering the JSON into
305 JavaScript in templates, and should typically remain enabled.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 306–345why, one step back
306
307 Default: ``True``308309.. py:data:: JSON_SORT_KEYS310311 Sort the keys of JSON objects alphabetically. This is useful for caching312 because it ensures the data is serialized the same way no matter what313 Python's hash seed is. While not recommended, you can disable this for a314 possible performance improvement at the cost of caching.315316 Default: ``True``317318.. py:data:: JSONIFY_PRETTYPRINT_REGULAR319320 ``jsonify`` responses will be output with newlines, spaces, and indentation321 for easier reading by humans. Always enabled in debug mode.322323 Default: ``False``324325.. py:data:: JSONIFY_MIMETYPE326327 The mimetype of ``jsonify`` responses.328329 Default: ``'application/json'``330331.. py:data:: TEMPLATES_AUTO_RELOAD332333 Reload templates when they are changed. If not set, it will be enabled in334 debug mode.335336 Default: ``None``337338.. py:data:: EXPLAIN_TEMPLATE_LOADING339340 Log debugging information tracing how a template file was loaded. This can341 be useful to figure out why a template was not loaded or the wrong file342 appears to be loaded.343344 Default: ``False``345

Merge pull request #2693 from davidism/max-cookie-sizeDavid Lordbefore adoptiond8bf589

lines 346–351why, one step back
346.. py:data:: MAX_COOKIE_SIZE
347348 Warn if cookie headers are larger than this many bytes. Defaults to349 ``4093``. Larger cookies may be silently ignored by browsers. Set to350 ``0`` to disable the warning.351

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 352–378why, one step back
352.. versionadded:: 0.4
353 ``LOGGER_NAME``354355.. versionadded:: 0.5356 ``SERVER_NAME``357358.. versionadded:: 0.6359 ``MAX_CONTENT_LENGTH``360361.. versionadded:: 0.7362 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``363364.. versionadded:: 0.8365 ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,366 ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,367 ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,368 ``SESSION_COOKIE_SECURE``369370.. versionadded:: 0.9371 ``PREFERRED_URL_SCHEME``372373.. versionadded:: 0.10374 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``375376.. versionadded:: 0.11377 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,378 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``

Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469

lines 379–382why, one step back
379
380.. versionchanged:: 1.0381 ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See382 :ref:`logging` for information about configuration.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 383–386why, one step back
383
384 Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment385 variable.386

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

lines 387–388why, one step back
387 Added :data:`SESSION_COOKIE_SAMESITE` to control the session
388 cookie's ``SameSite`` option.

Merge pull request #2693 from davidism/max-cookie-sizeDavid Lordbefore adoptiond8bf589

lines 389–390why, one step back
389
390 Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 391why, one step back
391

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

line 392why, one step back
392

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 393–421why, one step back
393Configuring from Files
394----------------------395396Configuration becomes more useful if you can store it in a separate file,397ideally located outside the actual application package. This makes398packaging and distributing your application possible via various package399handling tools (:ref:`distribute-deployment`) and finally modifying the400configuration file afterwards.401402So a common pattern is this::403404 app = Flask(__name__)405 app.config.from_object('yourapplication.default_settings')406 app.config.from_envvar('YOURAPPLICATION_SETTINGS')407408This first loads the configuration from the409`yourapplication.default_settings` module and then overrides the values410with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`411environment variable points to. This environment variable can be set on412Linux or OS X with the export command in the shell before starting the413server::414415 $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg416 $ python run-app.py417 * Running on http://127.0.0.1:5000/418 * Restarting with reloader...419420On Windows systems use the `set` builtin instead::421

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 422why, one step back
422 > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 423–431why, one step back
423
424The configuration files themselves are actual Python files. Only values425in uppercase are actually stored in the config object later on. So make426sure to use uppercase letters for your config keys.427428Here is an example of a configuration file::429430 # Example configuration431 DEBUG = False

Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d

line 432why, one step back
432 SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 433–439why, one step back
433
434Make sure to load the configuration very early on, so that extensions have435the ability to access the configuration when starting up. There are other436methods on the config object as well to load from individual files. For a437complete reference, read the :class:`~flask.Config` object's438documentation.439

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 440why, one step back
440

Merge pull request #2366 from tristanfisher/masterDavid Lordbefore adoption094b116

lines 441–450why, one step back
441Configuring from Environment Variables
442--------------------------------------443444In addition to pointing to configuration files using environment variables, you445may find it useful (or necessary) to control your configuration values directly446from the environment.447448Environment variables can be set on Linux or OS X with the export command in449the shell before starting the server::450

Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d

line 451why, one step back
451 $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f'

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 452why, one step back
452 $ export MAIL_ENABLED=false

Merge pull request #2366 from tristanfisher/masterDavid Lordbefore adoption094b116

lines 453–455why, one step back
453 $ python run-app.py
454 * Running on http://127.0.0.1:5000/455

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 456why, one step back
456On Windows systems use the ``set`` builtin instead::

Merge pull request #2366 from tristanfisher/masterDavid Lordbefore adoption094b116

line 457why, one step back
457

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 458why, one step back
458 > set SECRET_KEY='5f352379324c22463451387a0aec5d2f'

Merge pull request #2366 from tristanfisher/masterDavid Lordbefore adoption094b116

lines 459–467why, one step back
459
460While this approach is straightforward to use, it is important to remember that461environment variables are strings -- they are not automatically deserialized462into Python types.463464Here is an example of a configuration file that uses environment variables::465466 import os467

Merge branch '1.0.x'David Lordbefore adoption2236ba9

lines 468–469why, one step back
468 _mail_enabled = os.environ.get("MAIL_ENABLED", default="true")
469 MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}

Merge pull request #2366 from tristanfisher/masterDavid Lordbefore adoption094b116

line 470why, one step back
470

Merge branch '1.0.x'David Lordbefore adoption2236ba9

lines 471–472why, one step back
471 SECRET_KEY = os.environ.get("SECRET_KEY")
472

Merge pull request #2366 from tristanfisher/masterDavid Lordbefore adoption094b116

line 473why, one step back
473 if not SECRET_KEY:

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 474why, one step back
474 raise ValueError("No SECRET_KEY set for Flask application")

Merge pull request #2366 from tristanfisher/masterDavid Lordbefore adoption094b116

lines 475–484why, one step back
475
476477Notice that any value besides an empty string will be interpreted as a boolean478``True`` value in Python, which requires care if an environment explicitly sets479values intended to be ``False``.480481Make sure to load the configuration very early on, so that extensions have the482ability to access the configuration when starting up. There are other methods483on the config object as well to load from individual files. For a complete484reference, read the :class:`~flask.Config` class documentation.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

line 485why, one step back
485

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 486why, one step back
486

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 487–496why, one step back
487Configuration Best Practices
488----------------------------489490The downside with the approach mentioned earlier is that it makes testing491a little harder. There is no single 100% solution for this problem in492general, but there are a couple of things you can keep in mind to improve493that experience:4944951. Create your application in a function and register blueprints on it.496 That way you can create multiple instances of your application with

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 497why, one step back
497 different configurations attached which makes unit testing a lot

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 498–529why, one step back
498 easier. You can use this to pass in configuration as needed.
4995002. Do not write code that needs the configuration at import time. If you501 limit yourself to request-only accesses to the configuration you can502 reconfigure the object later on as needed.503504.. _config-dev-prod:505506Development / Production507------------------------508509Most applications need more than one configuration. There should be at510least separate configurations for the production server and the one used511during development. The easiest way to handle this is to use a default512configuration that is always loaded and part of the version control, and a513separate configuration that overrides the values as necessary as mentioned514in the example above::515516 app = Flask(__name__)517 app.config.from_object('yourapplication.default_settings')518 app.config.from_envvar('YOURAPPLICATION_SETTINGS')519520Then you just have to add a separate :file:`config.py` file and export521``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However522there are alternative ways as well. For example you could use imports or523subclassing.524525What is very popular in the Django world is to make the import explicit in526the config file by adding ``from yourapplication.default_settings527import *`` to the top of the file and then overriding the changes by hand.528You could also inspect an environment variable like529``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 530why, one step back
530and import different hard-coded files based on that.

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 531–537why, one step back
531
532An interesting pattern is also to use classes and inheritance for533configuration::534535 class Config(object):536 DEBUG = False537 TESTING = False

Merge pull request #2381 from trirpi/documentation-sqlite-uri-bugAnthony Plunkettbefore adoption45c8fb3

line 538why, one step back
538 DATABASE_URI = 'sqlite:///:memory:'

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 539–553why, one step back
539
540 class ProductionConfig(Config):541 DATABASE_URI = 'mysql://user@localhost/foo'542543 class DevelopmentConfig(Config):544 DEBUG = True545546 class TestingConfig(Config):547 TESTING = True548549To enable such a config you just have to call into550:meth:`~flask.Config.from_object`::551552 app.config.from_object('configmodule.ProductionConfig')553

Merge branch '1.0-maintenance'David Lordbefore adoptionac6746d

lines 554–565why, one step back
554Note that :meth:`~flask.Config.from_object` does not instantiate the class
555object. If you need to instantiate the class, such as to access a property,556then you must do so before calling :meth:`~flask.Config.from_object`::557558 from configmodule import ProductionConfig559 app.config.from_object(ProductionConfig())560561 # Alternatively, import via string:562 from werkzeug.utils import import_string563 cfg = import_string('configmodule.ProductionConfig')()564 app.config.from_object(cfg)565

Merge pull request #3103 from tbm/typosDavid Lordbefore adoption86bf9dc

line 566why, one step back
566Instantiating the configuration object allows you to use ``@property`` in

Merge branch '1.0-maintenance'David Lordbefore adoptionac6746d

lines 567–591why, one step back
567your configuration classes::
568569 class Config(object):570 """Base config, uses staging database server."""571 DEBUG = False572 TESTING = False573 DB_SERVER = '192.168.1.56'574575 @property576 def DATABASE_URI(self): # Note: all caps577 return 'mysql://user@{}/foo'.format(self.DB_SERVER)578579 class ProductionConfig(Config):580 """Uses production database server."""581 DB_SERVER = '192.168.19.32'582583 class DevelopmentConfig(Config):584 DB_SERVER = 'localhost'585 DEBUG = True586587 class TestingConfig(Config):588 DB_SERVER = 'localhost'589 DEBUG = True590 DATABASE_URI = 'sqlite:///:memory:'591

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 592–609why, one step back
592There are many different ways and it's up to you how you want to manage
593your configuration files. However here a list of good recommendations:594595- Keep a default configuration in version control. Either populate the596 config with this default configuration or import it in your own597 configuration files before overriding values.598- Use an environment variable to switch between the configurations.599 This can be done from outside the Python interpreter and makes600 development and deployment much easier because you can quickly and601 easily switch between different configs without having to touch the602 code at all. If you are working often on different projects you can603 even create your own script for sourcing that activates a virtualenv604 and exports the development configuration for you.605- Use a tool like `fabric`_ in production to push code and606 configurations separately to the production server(s). For some607 details about how to do that, head over to the608 :ref:`fabric-deployment` pattern.609

Merge pull request #2969 from codeaditya/update-linksDavid Lordbefore adoption7e714bd

line 610why, one step back
610.. _fabric: https://www.fabfile.org/

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 611–674why, one step back
611
612613.. _instance-folders:614615Instance Folders616----------------617618.. versionadded:: 0.8619620Flask 0.8 introduces instance folders. Flask for a long time made it621possible to refer to paths relative to the application's folder directly622(via :attr:`Flask.root_path`). This was also how many developers loaded623configurations stored next to the application. Unfortunately however this624only works well if applications are not packages in which case the root625path refers to the contents of the package.626627With Flask 0.8 a new attribute was introduced:628:attr:`Flask.instance_path`. It refers to a new concept called the629“instance folder”. The instance folder is designed to not be under630version control and be deployment specific. It's the perfect place to631drop things that either change at runtime or configuration files.632633You can either explicitly provide the path of the instance folder when634creating the Flask application or you can let Flask autodetect the635instance folder. For explicit configuration use the `instance_path`636parameter::637638 app = Flask(__name__, instance_path='/path/to/instance/folder')639640Please keep in mind that this path *must* be absolute when provided.641642If the `instance_path` parameter is not provided the following default643locations are used:644645- Uninstalled module::646647 /myapp.py648 /instance649650- Uninstalled package::651652 /myapp653 /__init__.py654 /instance655656- Installed module or package::657658 $PREFIX/lib/python2.X/site-packages/myapp659 $PREFIX/var/myapp-instance660661 ``$PREFIX`` is the prefix of your Python installation. This can be662 ``/usr`` or the path to your virtualenv. You can print the value of663 ``sys.prefix`` to see what the prefix is set to.664665Since the config object provided loading of configuration files from666relative filenames we made it possible to change the loading via filenames667to be relative to the instance path if wanted. The behavior of relative668paths in config files can be flipped between “relative to the application669root” (the default) to “relative to instance folder” via the670`instance_relative_config` switch to the application constructor::671672 app = Flask(__name__, instance_relative_config=True)673674Here is a full example of how to configure Flask to preload the config

Merge branch '1.0-maintenance'David Lordbefore adoptionac6746d

line 675why, one step back
675from a module and then override the config from a file in the instance

Merge pull request #2353 from grantwwu/patch-1David Lordbefore adoption49f3e96

lines 676–694why, one step back
676folder if it exists::
677678 app = Flask(__name__, instance_relative_config=True)679 app.config.from_object('yourapplication.default_settings')680 app.config.from_pyfile('application.cfg', silent=True)681682The path to the instance folder can be found via the683:attr:`Flask.instance_path`. Flask also provides a shortcut to open a684file from the instance folder with :meth:`Flask.open_instance_resource`.685686Example usage for both::687688 filename = os.path.join(app.instance_path, 'application.cfg')689 with open(filename) as f:690 config = f.read()691692 # or via open_instance_resource:693 with app.open_instance_resource('application.cfg') as f:694 config = f.read()