File: config.rst

package info (click to toggle)
flask 3.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,536 kB
  • sloc: python: 10,083; makefile: 32; sql: 22; sh: 19
file content (839 lines) | stat: -rw-r--r-- 29,011 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
Configuration Handling
======================

Applications need some kind of configuration.  There are different settings
you might want to change depending on the application environment like
toggling the debug mode, setting the secret key, and other such
environment-specific things.

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

Independent of how you load your config, there is a config object
available which holds the loaded configuration values:
The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`
object.  This is the place where Flask itself puts certain configuration
values and also where extensions can put their configuration values.  But
this is also where you can have your own configuration.


Configuration Basics
--------------------

The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and
can be modified just like any dictionary::

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

Certain configuration values are also forwarded to the
:attr:`~flask.Flask` object so you can read and write them from there::

    app.testing = True

To update multiple keys at once you can use the :meth:`dict.update`
method::

    app.config.update(
        TESTING=True,
        SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
    )


Debug Mode
----------

The :data:`DEBUG` config value is special because it may behave inconsistently if
changed after the app has begun setting up. In order to set debug mode reliably, use the
``--debug`` option on the ``flask`` or ``flask run`` command. ``flask run`` will use the
interactive debugger and reloader by default in debug mode.

.. code-block:: text

    $ flask --app hello run --debug

Using the option is recommended. While it is possible to set :data:`DEBUG` in your
config or code, this is strongly discouraged. It can't be read early by the
``flask run`` command, and some systems or extensions may have already configured
themselves based on a previous value.


Builtin Configuration Values
----------------------------

The following configuration values are used internally by Flask:

.. py:data:: DEBUG

    Whether debug mode is enabled. When using ``flask run`` to start the development
    server, an interactive debugger will be shown for unhandled exceptions, and the
    server will be reloaded when code changes. The :attr:`~flask.Flask.debug` attribute
    maps to this config key. This is set with the ``FLASK_DEBUG`` environment variable.
    It may not behave as expected if set in code.

    **Do not enable debug mode when deploying in production.**

    Default: ``False``

.. py:data:: TESTING

    Enable testing mode. Exceptions are propagated rather than handled by the
    the app's error handlers. Extensions may also change their behavior to
    facilitate easier testing. You should enable this in your own tests.

    Default: ``False``

.. py:data:: PROPAGATE_EXCEPTIONS

    Exceptions are re-raised rather than being handled by the app's error
    handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG``
    is enabled.

    Default: ``None``

.. py:data:: TRAP_HTTP_EXCEPTIONS

    If there is no handler for an ``HTTPException``-type exception, re-raise it
    to be handled by the interactive debugger instead of returning it as a
    simple error response.

    Default: ``False``

.. py:data:: TRAP_BAD_REQUEST_ERRORS

    Trying to access a key that doesn't exist from request dicts like ``args``
    and ``form`` will return a 400 Bad Request error page. Enable this to treat
    the error as an unhandled exception instead so that you get the interactive
    debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If
    unset, it is enabled in debug mode.

    Default: ``None``

.. py:data:: SECRET_KEY

    A secret key that will be used for securely signing the session cookie
    and can be used for any other security related needs by extensions or your
    application. It should be a long random ``bytes`` or ``str``. For
    example, copy the output of this to your config::

        $ python -c 'import secrets; print(secrets.token_hex())'
        '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'

    **Do not reveal the secret key when posting questions or committing code.**

    Default: ``None``

.. py:data:: SECRET_KEY_FALLBACKS

    A list of old secret keys that can still be used for unsigning. This allows
    a project to implement key rotation without invalidating active sessions or
    other recently-signed secrets.

    Keys should be removed after an appropriate period of time, as checking each
    additional key adds some overhead.

    Order should not matter, but the default implementation will test the last
    key in the list first, so it might make sense to order oldest to newest.

    Flask's built-in secure cookie session supports this. Extensions that use
    :data:`SECRET_KEY` may not support this yet.

    Default: ``None``

    .. versionadded:: 3.1

.. py:data:: SESSION_COOKIE_NAME

    The name of the session cookie. Can be changed in case you already have a
    cookie with the same name.

    Default: ``'session'``

.. py:data:: SESSION_COOKIE_DOMAIN

    The value of the ``Domain`` parameter on the session cookie. If not set, browsers
    will only send the cookie to the exact domain it was set from. Otherwise, they
    will send it to any subdomain of the given value as well.

    Not setting this value is more restricted and secure than setting it.

    Default: ``None``

    .. warning::
        If this is changed after the browser created a cookie is created with
        one setting, it may result in another being created. Browsers may send
        send both in an undefined order. In that case, you may want to change
        :data:`SESSION_COOKIE_NAME` as well or otherwise invalidate old sessions.

    .. versionchanged:: 2.3
        Not set by default, does not fall back to ``SERVER_NAME``.

.. py:data:: SESSION_COOKIE_PATH

    The path that the session cookie will be valid for. If not set, the cookie
    will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.

    Default: ``None``

.. py:data:: SESSION_COOKIE_HTTPONLY

    Browsers will not allow JavaScript access to cookies marked as "HTTP only"
    for security.

    Default: ``True``

.. py:data:: SESSION_COOKIE_SECURE

    Browsers will only send cookies with requests over HTTPS if the cookie is
    marked "secure". The application must be served over HTTPS for this to make
    sense.

    Default: ``False``

.. py:data:: SESSION_COOKIE_PARTITIONED

    Browsers will send cookies based on the top-level document's domain, rather
    than only the domain of the document setting the cookie. This prevents third
    party cookies set in iframes from "leaking" between separate sites.

    Browsers are beginning to disallow non-partitioned third party cookies, so
    you need to mark your cookies partitioned if you expect them to work in such
    embedded situations.

    Enabling this implicitly enables :data:`SESSION_COOKIE_SECURE` as well, as
    it is only valid when served over HTTPS.

    Default: ``False``

    .. versionadded:: 3.1

.. py:data:: SESSION_COOKIE_SAMESITE

    Restrict how cookies are sent with requests from external sites. Can
    be set to ``'Lax'`` (recommended) or ``'Strict'``.
    See :ref:`security-cookie`.

    Default: ``None``

    .. versionadded:: 1.0

.. py:data:: PERMANENT_SESSION_LIFETIME

    If ``session.permanent`` is true, the cookie's expiration will be set this
    number of seconds in the future. Can either be a
    :class:`datetime.timedelta` or an ``int``.

    Flask's default cookie implementation validates that the cryptographic
    signature is not older than this value.

    Default: ``timedelta(days=31)`` (``2678400`` seconds)

.. py:data:: SESSION_REFRESH_EACH_REQUEST

    Control whether the cookie is sent with every response when
    ``session.permanent`` is true. Sending the cookie every time (the default)
    can more reliably keep the session from expiring, but uses more bandwidth.
    Non-permanent sessions are not affected.

    Default: ``True``

.. py:data:: USE_X_SENDFILE

    When serving files, set the ``X-Sendfile`` header instead of serving the
    data with Flask. Some web servers, such as Apache, recognize this and serve
    the data more efficiently. This only makes sense when using such a server.

    Default: ``False``

.. py:data:: SEND_FILE_MAX_AGE_DEFAULT

    When serving files, set the cache control max age to this number of
    seconds. Can be a :class:`datetime.timedelta` or an ``int``.
    Override this value on a per-file basis using
    :meth:`~flask.Flask.get_send_file_max_age` on the application or
    blueprint.

    If ``None``, ``send_file`` tells the browser to use conditional
    requests will be used instead of a timed cache, which is usually
    preferable.

    Default: ``None``

.. py:data:: TRUSTED_HOSTS

    Validate :attr:`.Request.host` and other attributes that use it against
    these trusted values. Raise a :exc:`~werkzeug.exceptions.SecurityError` if
    the host is invalid, which results in a 400 error. If it is ``None``, all
    hosts are valid. Each value is either an exact match, or can start with
    a dot ``.`` to match any subdomain.

    Validation is done during routing against this value. ``before_request`` and
    ``after_request`` callbacks will still be called.

    Default: ``None``

    .. versionadded:: 3.1

.. py:data:: SERVER_NAME

    Inform the application what host and port it is bound to.

    Must be set if ``subdomain_matching`` is enabled, to be able to extract the
    subdomain from the request.

    Must be set for ``url_for`` to generate external URLs outside of a
    request context.

    Default: ``None``

    .. versionchanged:: 3.1
        Does not restrict requests to only this domain, for both
        ``subdomain_matching`` and ``host_matching``.

    .. versionchanged:: 1.0
        Does not implicitly enable ``subdomain_matching``.

    .. versionchanged:: 2.3
        Does not affect ``SESSION_COOKIE_DOMAIN``.

.. py:data:: APPLICATION_ROOT

    Inform the application what path it is mounted under by the application /
    web server.  This is used for generating URLs outside the context of a
    request (inside a request, the dispatcher is responsible for setting
    ``SCRIPT_NAME`` instead; see :doc:`/patterns/appdispatch`
    for examples of dispatch configuration).

    Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not
    set.

    Default: ``'/'``

.. py:data:: PREFERRED_URL_SCHEME

    Use this scheme for generating external URLs when not in a request context.

    Default: ``'http'``

.. py:data:: MAX_CONTENT_LENGTH

    The maximum number of bytes that will be read during this request. If
    this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge`
    error is raised. If it is set to ``None``, no limit is enforced at the
    Flask application level. However, if it is ``None`` and the request has no
    ``Content-Length`` header and the WSGI server does not indicate that it
    terminates the stream, then no data is read to avoid an infinite stream.

    Each request defaults to this config. It can be set on a specific
    :attr:`.Request.max_content_length` to apply the limit to that specific
    view. This should be set appropriately based on an application's or view's
    specific needs.

    Default: ``None``

    .. versionadded:: 0.6

.. py:data:: MAX_FORM_MEMORY_SIZE

    The maximum size in bytes any non-file form field may be in a
    ``multipart/form-data`` body. If this limit is exceeded, a 413
    :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it is
    set to ``None``, no limit is enforced at the Flask application level.

    Each request defaults to this config. It can be set on a specific
    :attr:`.Request.max_form_memory_parts` to apply the limit to that specific
    view. This should be set appropriately based on an application's or view's
    specific needs.

    Default: ``500_000``

    .. versionadded:: 3.1

.. py:data:: MAX_FORM_PARTS

    The maximum number of fields that may be present in a
    ``multipart/form-data`` body. If this limit is exceeded, a 413
    :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it
    is set to ``None``, no limit is enforced at the Flask application level.

    Each request defaults to this config. It can be set on a specific
    :attr:`.Request.max_form_parts` to apply the limit to that specific view.
    This should be set appropriately based on an application's or view's
    specific needs.

    Default: ``1_000``

    .. versionadded:: 3.1

.. py:data:: TEMPLATES_AUTO_RELOAD

    Reload templates when they are changed. If not set, it will be enabled in
    debug mode.

    Default: ``None``

.. py:data:: EXPLAIN_TEMPLATE_LOADING

    Log debugging information tracing how a template file was loaded. This can
    be useful to figure out why a template was not loaded or the wrong file
    appears to be loaded.

    Default: ``False``

.. py:data:: MAX_COOKIE_SIZE

    Warn if cookie headers are larger than this many bytes. Defaults to
    ``4093``. Larger cookies may be silently ignored by browsers. Set to
    ``0`` to disable the warning.

.. py:data:: PROVIDE_AUTOMATIC_OPTIONS

    Set to ``False`` to disable the automatic addition of OPTIONS
    responses. This can be overridden per route by altering the
    ``provide_automatic_options`` attribute.

.. versionadded:: 0.4
   ``LOGGER_NAME``

.. versionadded:: 0.5
   ``SERVER_NAME``

.. versionadded:: 0.6
   ``MAX_CONTENT_LENGTH``

.. versionadded:: 0.7
   ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``

.. versionadded:: 0.8
   ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,
   ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,
   ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,
   ``SESSION_COOKIE_SECURE``

.. versionadded:: 0.9
   ``PREFERRED_URL_SCHEME``

.. versionadded:: 0.10
   ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``

.. versionadded:: 0.11
   ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,
   ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``

.. versionchanged:: 1.0
    ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See
    :doc:`/logging` for information about configuration.

    Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment
    variable.

    Added :data:`SESSION_COOKIE_SAMESITE` to control the session
    cookie's ``SameSite`` option.

    Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.

.. versionchanged:: 2.2
    Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``.

.. versionchanged:: 2.3
    ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_MIMETYPE``, and
    ``JSONIFY_PRETTYPRINT_REGULAR`` were removed. The default ``app.json`` provider has
    equivalent attributes instead.

.. versionchanged:: 2.3
    ``ENV`` was removed.

.. versionadded:: 3.10
    Added :data:`PROVIDE_AUTOMATIC_OPTIONS` to control the default
    addition of autogenerated OPTIONS responses.


Configuring from Python Files
-----------------------------

Configuration becomes more useful if you can store it in a separate file, ideally
located outside the actual application package. You can deploy your application, then
separately configure it for the specific deployment.

A common pattern is this::

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

This first loads the configuration from the
`yourapplication.default_settings` module and then overrides the values
with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`
environment variable points to.  This environment variable can be set
in the shell before starting the server:

.. tabs::

   .. group-tab:: Bash

      .. code-block:: text

         $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
         $ flask run
          * Running on http://127.0.0.1:5000/

   .. group-tab:: Fish

      .. code-block:: text

         $ set -x YOURAPPLICATION_SETTINGS /path/to/settings.cfg
         $ flask run
          * Running on http://127.0.0.1:5000/

   .. group-tab:: CMD

      .. code-block:: text

         > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
         > flask run
          * Running on http://127.0.0.1:5000/

   .. group-tab:: Powershell

      .. code-block:: text

         > $env:YOURAPPLICATION_SETTINGS = "\path\to\settings.cfg"
         > flask run
          * Running on http://127.0.0.1:5000/

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

Here is an example of a configuration file::

    # Example configuration
    SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'

Make sure to load the configuration very early on, so that extensions have
the ability to access the configuration when starting up.  There are other
methods on the config object as well to load from individual files.  For a
complete reference, read the :class:`~flask.Config` object's
documentation.


Configuring from Data Files
---------------------------

It is also possible to load configuration from a file in a format of
your choice using :meth:`~flask.Config.from_file`. For example to load
from a TOML file:

.. code-block:: python

    import tomllib
    app.config.from_file("config.toml", load=tomllib.load, text=False)

Or from a JSON file:

.. code-block:: python

    import json
    app.config.from_file("config.json", load=json.load)


Configuring from Environment Variables
--------------------------------------

In addition to pointing to configuration files using environment
variables, you may find it useful (or necessary) to control your
configuration values directly from the environment. Flask can be
instructed to load all environment variables starting with a specific
prefix into the config using :meth:`~flask.Config.from_prefixed_env`.

Environment variables can be set in the shell before starting the
server:

.. tabs::

   .. group-tab:: Bash

      .. code-block:: text

         $ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"
         $ export FLASK_MAIL_ENABLED=false
         $ flask run
          * Running on http://127.0.0.1:5000/

   .. group-tab:: Fish

      .. code-block:: text

         $ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f"
         $ set -x FLASK_MAIL_ENABLED false
         $ flask run
          * Running on http://127.0.0.1:5000/

   .. group-tab:: CMD

      .. code-block:: text

         > set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"
         > set FLASK_MAIL_ENABLED=false
         > flask run
          * Running on http://127.0.0.1:5000/

   .. group-tab:: Powershell

      .. code-block:: text

         > $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f"
         > $env:FLASK_MAIL_ENABLED = "false"
         > flask run
          * Running on http://127.0.0.1:5000/

The variables can then be loaded and accessed via the config with a key
equal to the environment variable name without the prefix i.e.

.. code-block:: python

    app.config.from_prefixed_env()
    app.config["SECRET_KEY"]  # Is "5f352379324c22463451387a0aec5d2f"

The prefix is ``FLASK_`` by default. This is configurable via the
``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.

Values will be parsed to attempt to convert them to a more specific type
than strings. By default :func:`json.loads` is used, so any valid JSON
value is possible, including lists and dicts. This is configurable via
the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.

When adding a boolean value with the default JSON parsing, only "true"
and "false", lowercase, are valid values. Keep in mind that any
non-empty string is considered ``True`` by Python.

It is possible to set keys in nested dictionaries by separating the
keys with double underscore (``__``). Any intermediate keys that don't
exist on the parent dict will be initialized to an empty dict.

.. code-block:: text

    $ export FLASK_MYAPI__credentials__username=user123

.. code-block:: python

    app.config["MYAPI"]["credentials"]["username"]  # Is "user123"

On Windows, environment variable keys are always uppercase, therefore
the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``.

For even more config loading features, including merging and
case-insensitive Windows support, try a dedicated library such as
Dynaconf_, which includes integration with Flask.

.. _Dynaconf: https://www.dynaconf.com/


Configuration Best Practices
----------------------------

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

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

2.  Do not write code that needs the configuration at import time.  If you
    limit yourself to request-only accesses to the configuration you can
    reconfigure the object later on as needed.

3.  Make sure to load the configuration very early on, so that
    extensions can access the configuration when calling ``init_app``.


.. _config-dev-prod:

Development / Production
------------------------

Most applications need more than one configuration.  There should be at
least separate configurations for the production server and the one used
during development.  The easiest way to handle this is to use a default
configuration that is always loaded and part of the version control, and a
separate configuration that overrides the values as necessary as mentioned
in the example above::

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

Then you just have to add a separate :file:`config.py` file and export
``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done.  However
there are alternative ways as well.  For example you could use imports or
subclassing.

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

An interesting pattern is also to use classes and inheritance for
configuration::

    class Config(object):
        TESTING = False

    class ProductionConfig(Config):
        DATABASE_URI = 'mysql://user@localhost/foo'

    class DevelopmentConfig(Config):
        DATABASE_URI = "sqlite:////tmp/foo.db"

    class TestingConfig(Config):
        DATABASE_URI = 'sqlite:///:memory:'
        TESTING = True

To enable such a config you just have to call into
:meth:`~flask.Config.from_object`::

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

Note that :meth:`~flask.Config.from_object` does not instantiate the class
object. If you need to instantiate the class, such as to access a property,
then you must do so before calling :meth:`~flask.Config.from_object`::

    from configmodule import ProductionConfig
    app.config.from_object(ProductionConfig())

    # Alternatively, import via string:
    from werkzeug.utils import import_string
    cfg = import_string('configmodule.ProductionConfig')()
    app.config.from_object(cfg)

Instantiating the configuration object allows you to use ``@property`` in
your configuration classes::

    class Config(object):
        """Base config, uses staging database server."""
        TESTING = False
        DB_SERVER = '192.168.1.56'

        @property
        def DATABASE_URI(self):  # Note: all caps
            return f"mysql://user@{self.DB_SERVER}/foo"

    class ProductionConfig(Config):
        """Uses production database server."""
        DB_SERVER = '192.168.19.32'

    class DevelopmentConfig(Config):
        DB_SERVER = 'localhost'

    class TestingConfig(Config):
        DB_SERVER = 'localhost'
        DATABASE_URI = 'sqlite:///:memory:'

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

-   Keep a default configuration in version control.  Either populate the
    config with this default configuration or import it in your own
    configuration files before overriding values.
-   Use an environment variable to switch between the configurations.
    This can be done from outside the Python interpreter and makes
    development and deployment much easier because you can quickly and
    easily switch between different configs without having to touch the
    code at all.  If you are working often on different projects you can
    even create your own script for sourcing that activates a virtualenv
    and exports the development configuration for you.
-   Use a tool like `fabric`_ to push code and configuration separately
    to the production server(s).

.. _fabric: https://www.fabfile.org/


.. _instance-folders:

Instance Folders
----------------

.. versionadded:: 0.8

Flask 0.8 introduces instance folders.  Flask for a long time made it
possible to refer to paths relative to the application's folder directly
(via :attr:`Flask.root_path`).  This was also how many developers loaded
configurations stored next to the application.  Unfortunately however this
only works well if applications are not packages in which case the root
path refers to the contents of the package.

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

You can either explicitly provide the path of the instance folder when
creating the Flask application or you can let Flask autodetect the
instance folder.  For explicit configuration use the `instance_path`
parameter::

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

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

If the `instance_path` parameter is not provided the following default
locations are used:

-   Uninstalled module::

        /myapp.py
        /instance

-   Uninstalled package::

        /myapp
            /__init__.py
        /instance

-   Installed module or package::

        $PREFIX/lib/pythonX.Y/site-packages/myapp
        $PREFIX/var/myapp-instance

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

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

    app = Flask(__name__, instance_relative_config=True)

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

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

The path to the instance folder can be found via the
:attr:`Flask.instance_path`.  Flask also provides a shortcut to open a
file from the instance folder with :meth:`Flask.open_instance_resource`.

Example usage for both::

    filename = os.path.join(app.instance_path, 'application.cfg')
    with open(filename) as f:
        config = f.read()

    # or via open_instance_resource:
    with app.open_instance_resource('application.cfg') as f:
        config = f.read()