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 fileTake it
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 be12available when the application starts up. You can hard code the13configuration in the code, which for many small applications is not14actually 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.222324Configuration Basics25--------------------2627The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and28can be modified just like any dictionary::2930 app = Flask(__name__)31 app.config['TESTING'] = True3233Certain configuration values are also forwarded to the34:attr:`~flask.Flask` object so you can read and write them from there::3536 app.testing = True3738To update multiple keys at once you can use the :meth:`dict.update`39method::4041 app.config.update(42 TESTING=True,43 SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/'44 )454647Environment and Debug Features48------------------------------4950The :data:`ENV` and :data:`DEBUG` config values are special because they51may behave inconsistently if changed after the app has begun setting up.52In order to set the environment and debug mode reliably, Flask uses53environment variables.5455The environment is used to indicate to Flask, extensions, and other56programs, like Sentry, what context Flask is running in. It is57controlled with the :envvar:`FLASK_ENV` environment variable and58defaults to ``production``.5960Setting :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.6465.. versionchanged:: 1.066 Added :envvar:`FLASK_ENV` to control the environment separately67 from debug mode. The development environment enables debug mode.6869To switch Flask to the development environment and enable debug mode,70set :envvar:`FLASK_ENV`::7172 $ export FLASK_ENV=development73 $ flask run7475(On Windows, use ``set`` instead of ``export``.)7677Using the environment variables as described above is recommended. While78it 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.828384Builtin Configuration Values85----------------------------8687The following configuration values are used internally by Flask:8889.. py:data:: ENV9091 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.0102103.. py:data:: DEBUG104105 Whether debug mode is enabled. When using ``flask run`` to start the106 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.112113 **Do not enable debug mode when deploying in production.**114115 Default: ``True`` if :data:`ENV` is ``'development'``, or ``False``116 otherwise.117118.. 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``149150.. py:data:: TRAP_BAD_REQUEST_ERRORS151152 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::166167 $ python -c 'import os; print(os.urandom(16))'168 b'_5#y2L"F4Q8z\n\xec]/'169170 **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 not184 set, the cookie will be valid for all subdomains of :data:`SERVER_NAME`.185 If ``False``, the cookie's domain will not be set.186187 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``210211.. py:data:: SESSION_COOKIE_SAMESITE212213 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.0220221.. py:data:: PERMANENT_SESSION_LIFETIME222223 If ``session.permanent`` is true, the cookie's expiration will be set this224 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.229230 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_NAME259260 Inform the application what host and port it is bound to. Required261 for subdomain route matching support.262263 If set, will be used for the session cookie domain if264 :data:`SESSION_COOKIE_DOMAIN` is not set. Modern web browsers will265 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. ::268269 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`` by304 ``jsonify``. This has security implications when rendering the JSON into305 JavaScript in templates, and should typically remain enabled.306307 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``345346.. py:data:: MAX_COOKIE_SIZE347348 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.351352.. versionadded:: 0.4353 ``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``379380.. versionchanged:: 1.0381 ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See382 :ref:`logging` for information about configuration.383384 Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment385 variable.386387 Added :data:`SESSION_COOKIE_SAMESITE` to control the session388 cookie's ``SameSite`` option.389390 Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.391392393Configuring from Files394----------------------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::421422 > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg423424The 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 = False432 SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'433434Make 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.439440441Configuring from Environment Variables442--------------------------------------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::450451 $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f'452 $ export MAIL_ENABLED=false453 $ python run-app.py454 * Running on http://127.0.0.1:5000/455456On Windows systems use the ``set`` builtin instead::457458 > set SECRET_KEY='5f352379324c22463451387a0aec5d2f'459460While 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 os467468 _mail_enabled = os.environ.get("MAIL_ENABLED", default="true")469 MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}470471 SECRET_KEY = os.environ.get("SECRET_KEY")472473 if not SECRET_KEY:474 raise ValueError("No SECRET_KEY set for Flask application")475476477Notice 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.485486487Configuration Best Practices488----------------------------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 with497 different configurations attached which makes unit testing a lot498 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` etc530and import different hard-coded files based on that.531532An interesting pattern is also to use classes and inheritance for533configuration::534535 class Config(object):536 DEBUG = False537 TESTING = False538 DATABASE_URI = 'sqlite:///:memory:'539540 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')553554Note that :meth:`~flask.Config.from_object` does not instantiate the class555object. 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)565566Instantiating the configuration object allows you to use ``@property`` in567your 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:'591592There are many different ways and it's up to you how you want to manage593your 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.609610.. _fabric: https://www.fabfile.org/611612613.. _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 config675from a module and then override the config from a file in the instance676folder 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()