config.rst
This file
Path
docs/config.rst
384 lines · 16.3 KiB
Last changed by
Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption11c7b1d
History of this fileTake it
The walk stopped after 200 commits: lines older than de3b6ab point at it.
Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 1–7why, one step back1.. _config:23Configuration Handling4======================56.. versionadded:: 0.37Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptionf0c089f
lines 8–11why, one step back8Applications need some kind of configuration. There are different settings9you might want to change depending on the application environment like10toggling the debug mode, setting the secret key, and other such11environment-specific things.Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 12–34why, one step back1213The way Flask is designed usually requires the configuration to be14available when the application starts up. You can hardcode the15configuration in the code, which for many small applications is not16actually that bad, but there are better ways.1718Independent of how you load your config, there is a config object19available which holds the loaded configuration values:20The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`21object. This is the place where Flask itself puts certain configuration22values and also where extensions can put their configuration values. But23this is also where you can have your own configuration.2425Configuration Basics26--------------------2728The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and29can be modified just like any dictionary::3031 app = Flask(__name__)32 app.config['DEBUG'] = True3334Certain configuration values are also forwarded to theMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptionf0c089f
line 35why, one step back35:attr:`~flask.Flask` object so you can read and write them from there::Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 36–72why, one step back3637 app.debug = True3839To update multiple keys at once you can use the :meth:`dict.update`40method::4142 app.config.update(43 DEBUG=True,44 SECRET_KEY='...'45 )4647Builtin Configuration Values48----------------------------4950The following configuration values are used internally by Flask:5152.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|5354================================= =========================================55``DEBUG`` enable/disable debug mode56``TESTING`` enable/disable testing mode57``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the58 propagation of exceptions. If not set or59 explicitly set to `None` this is60 implicitly true if either `TESTING` or61 `DEBUG` is true.62``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in63 debug mode the request context is not64 popped on exceptions to enable debuggers65 to introspect the data. This can be66 disabled by this key. You can also use67 this setting to force-enable it for non68 debug execution which might be useful to69 debug production applications (but also70 very risky).71``SECRET_KEY`` the secret key72``SESSION_COOKIE_NAME`` the name of the session cookieAdded finer control over the session cookie parametersArmin Ronacherbefore adoptionccf4641
lines 73–86why, one step back73``SESSION_COOKIE_DOMAIN`` the domain for the session cookie. If74 this is not set, the cookie will be75 valid for all subdomains of76 ``SERVER_NAME``.77``SESSION_COOKIE_PATH`` the path for the session cookie. If78 this is not set the cookie will be valid79 for all of ``APPLICATION_ROOT`` or if80 that is not set for ``'/'``.81``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set82 with the httponly flag. Defaults to83 `True`.84``SESSION_COOKIE_SECURE`` controls if the cookie should be set85 with the secure flag. Defaults to86 `False`.Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 87–88why, one step back87``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as88 :class:`datetime.timedelta` object.PERMANENT_SESSION_LIFETIME can now be an integer. This fixes #310Armin Ronacherbefore adoption6dccf77
lines 89–90why, one step back89 Starting with Flask 0.8 this can also be90 an integer representing seconds.Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 91–94why, one step back91``USE_X_SENDFILE`` enable/disable x-sendfile92``LOGGER_NAME`` the name of the logger93``SERVER_NAME`` the name and port number of the server.94 Required for subdomain support (e.g.:Mention localhost:5000 being pointless in the docs. It already says that down on the page but not on the keyArmin Ronacherbefore adoption6d0b326
lines 95–96why, one step back95 ``'myapp.dev:5000'``) Note that96 localhost does not support subdomains soFixed a typo. "Does not" of courseArmin Ronacherbefore adoption396c4bd
lines 97–98why, one step back97 setting this to “localhost” does not98 help.Added the APPLICATION_ROOT configuration variable which is used by session backends.Armin Ronacherbefore adoptionc844d02
lines 99–105why, one step back99``APPLICATION_ROOT`` If the application does not occupy100 a whole domain or subdomain this can101 be set to the path where the application102 is configured to live. This is for103 session cookie as path value. If104 domains are used, this should be105 ``None``.Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 106–109why, one step back106``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will107 reject incoming requests with a108 content length greater than this by109 returning a 413 status code.Added HTTP exception trapping. This should fix #294Armin Ronacherbefore adoption7155f11
lines 110–117why, one step back110``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will111 not execute the error handlers of HTTP112 exceptions but instead treat the113 exception like any other and bubble it114 through the exception stack. This is115 helpful for hairy debugging situations116 where you have to find out where an HTTP117 exception is coming from.Don't only catch BadRequest key errors but all bad request errors.Armin Ronacherbefore adoptionacac64e
line 118why, one step back118``TRAP_BAD_REQUEST_ERRORS`` Werkzeug's internal data structures thatAdded HTTP exception trapping. This should fix #294Armin Ronacherbefore adoption7155f11
lines 119–120why, one step back119 deal with request specific data will120 raise special key errors that are alsoDon't only catch BadRequest key errors but all bad request errors.Armin Ronacherbefore adoptionacac64e
lines 121–126why, one step back121 bad request exceptions. Likewise many122 operations can implicitly fail with a123 BadRequest exception for consistency.124 Since it's nice for debugging to know125 why exactly it failed this flag can be126 used to debug those situations. If thisAdded HTTP exception trapping. This should fix #294Armin Ronacherbefore adoption7155f11
lines 127–128why, one step back127 config is set to ``True`` you will get128 a regular traceback instead.Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 129–160why, one step back129================================= =========================================130131.. admonition:: More on ``SERVER_NAME``132133 The ``SERVER_NAME`` key is used for the subdomain support. Because134 Flask cannot guess the subdomain part without the knowledge of the135 actual server name, this is required if you want to work with136 subdomains. This is also used for the session cookie.137138 Please keep in mind that not only Flask has the problem of not knowing139 what subdomains are, your web browser does as well. Most modern web140 browsers will not allow cross-subdomain cookies to be set on a141 server name without dots in it. So if your server name is142 ``'localhost'`` you will not be able to set a cookie for143 ``'localhost'`` and every subdomain of it. Please chose a different144 server name in that case, like ``'myapplication.local'`` and add145 this name + the subdomains you want to use into your host config146 or setup a local `bind`_.147148.. _bind: https://www.isc.org/software/bind149150.. versionadded:: 0.4151 ``LOGGER_NAME``152153.. versionadded:: 0.5154 ``SERVER_NAME``155156.. versionadded:: 0.6157 ``MAX_CONTENT_LENGTH``158159.. versionadded:: 0.7160 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``Added HTTP exception trapping. This should fix #294Armin Ronacherbefore adoption7155f11
lines 161–162why, one step back161162.. versionadded:: 0.8Added the APPLICATION_ROOT configuration variable which is used by session backends.Armin Ronacherbefore adoptionc844d02
line 163why, one step back163 ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,Added finer control over the session cookie parametersArmin Ronacherbefore adoptionccf4641
lines 164–166why, one step back164 ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,165 ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,166 ``SESSION_COOKIE_SECURE``Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 167–170why, one step back167168Configuring from Files169----------------------170Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptionf0c089f
lines 171–175why, one step back171Configuration becomes more useful if you can store it in a separate file,172ideally located outside the actual application package. This makes173packaging and distributing your application possible via various package174handling tools (:ref:`distribute-deployment`) and finally modifying the175configuration file afterwards.Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 176–202why, one step back176177So a common pattern is this::178179 app = Flask(__name__)180 app.config.from_object('yourapplication.default_settings')181 app.config.from_envvar('YOURAPPLICATION_SETTINGS')182183This first loads the configuration from the184`yourapplication.default_settings` module and then overrides the values185with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`186environment variable points to. This environment variable can be set on187Linux or OS X with the export command in the shell before starting the188server::189190 $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg191 $ python run-app.py192 * Running on http://127.0.0.1:5000/193 * Restarting with reloader...194195On Windows systems use the `set` builtin instead::196197 >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg198199The configuration files themselves are actual Python files. Only values200in uppercase are actually stored in the config object later on. So make201sure to use uppercase letters for your config keys.202Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptionf0c089f
line 203why, one step back203Here is an example of a configuration file::Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
line 204why, one step back204Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptionf0c089f
line 205why, one step back205 # Example configurationFixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 206–208why, one step back206 DEBUG = False207 SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'208Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptionf0c089f
line 209why, one step back209Make sure to load the configuration very early on, so that extensions haveFixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 210–219why, one step back210the ability to access the configuration when starting up. There are other211methods on the config object as well to load from individual files. For a212complete reference, read the :class:`~flask.Config` object's213documentation.214215216Configuration Best Practices217----------------------------218219The downside with the approach mentioned earlier is that it makes testingMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptionf0c089f
lines 220–222why, one step back220a little harder. There is no single 100% solution for this problem in221general, but there are a couple of things you can keep in mind to improve222that experience:Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 223–236why, one step back2232241. create your application in a function and register blueprints on it.225 That way you can create multiple instances of your application with226 different configurations attached which makes unittesting a lot227 easier. You can use this to pass in configuration as needed.2282292. Do not write code that needs the configuration at import time. If you230 limit yourself to request-only accesses to the configuration you can231 reconfigure the object later on as needed.232233234Development / Production235------------------------236Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoptionf0c089f
lines 237–240why, one step back237Most applications need more than one configuration. There should be at238least separate configurations for the production server and the one used239during development. The easiest way to handle this is to use a default240configuration that is always loaded and part of the version control, and aFixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 241–300why, one step back241separate configuration that overrides the values as necessary as mentioned242in the example above::243244 app = Flask(__name__)245 app.config.from_object('yourapplication.default_settings')246 app.config.from_envvar('YOURAPPLICATION_SETTINGS')247248Then you just have to add a separate `config.py` file and export249``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However250there are alternative ways as well. For example you could use imports or251subclassing.252253What is very popular in the Django world is to make the import explicit in254the config file by adding an ``from yourapplication.default_settings255import *`` to the top of the file and then overriding the changes by hand.256You could also inspect an environment variable like257``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc258and import different hardcoded files based on that.259260An interesting pattern is also to use classes and inheritance for261configuration::262263 class Config(object):264 DEBUG = False265 TESTING = False266 DATABASE_URI = 'sqlite://:memory:'267268 class ProductionConfig(Config):269 DATABASE_URI = 'mysql://user@localhost/foo'270 271 class DevelopmentConfig(Config):272 DEBUG = True273274 class TestingConfig(Config):275 TESTING = True276277To enable such a config you just have to call into278:meth:`~flask.Config.from_object`::279280 app.config.from_object('configmodule.ProductionConfig')281282There are many different ways and it's up to you how you want to manage283your configuration files. However here a list of good recommendations:284285- keep a default configuration in version control. Either populate the286 config with this default configuration or import it in your own287 configuration files before overriding values.288- use an environment variable to switch between the configurations.289 This can be done from outside the Python interpreter and makes290 development and deployment much easier because you can quickly and291 easily switch between different configs without having to touch the292 code at all. If you are working often on different projects you can293 even create your own script for sourcing that activates a virtualenv294 and exports the development configuration for you.295- Use a tool like `fabric`_ in production to push code and296 configurations separately to the production server(s). For some297 details about how to do that, head over to the298 :ref:`fabric-deployment` pattern.299300.. _fabric: http://fabfile.org/Documented instance rootArmin Ronacherbefore adoption187cb80
lines 301–322why, one step back301302303.. _instance-folders:304305Instance Folders306----------------307308.. versionadded:: 0.8309310Flask 0.8 introduces instance folders. Flask for a long time made it311possible to refer to paths relative to the application's folder directly312(via :attr:`Flask.root_path`). This was also how many developers loaded313configurations stored next to the application. Unfortunately however this314only works well if applications are not packages in which case the root315path refers to the contents of the package.316317With Flask 0.8 a new attribute was introduced:318:attr:`Flask.instance_path`. It refers to a new concept called the319“instance folder”. The instance folder is designed to not be under320version control and be deployment specific. It's the perfect place to321drop things that either change at runtime or configuration files.322Updated instance path documentation to explain the $PREFIX lookupArmin Ronacherbefore adoption314f920
lines 323–326why, one step back323You can either explicitly provide the path of the instance folder when324creating the Flask application or you can let Flask autodetect the325instance folder. For explicit configuration use the `instance_path`326parameter::Documented instance rootArmin Ronacherbefore adoption187cb80
line 327why, one step back327Mention default locations for instance foldersArmin Ronacherbefore adoption9af7554
lines 328–329why, one step back328 app = Flask(__name__, instance_path='/path/to/instance/folder')329Updated instance path documentation to explain the $PREFIX lookupArmin Ronacherbefore adoption314f920
line 330why, one step back330Please keep in mind that this path *must* be absolute when provided.Mention default locations for instance foldersArmin Ronacherbefore adoption9af7554
line 331why, one step back331Updated instance path documentation to explain the $PREFIX lookupArmin Ronacherbefore adoption314f920
lines 332–336why, one step back332If the `instance_path` parameter is not provided the following default333locations are used:334335- Uninstalled module::336Mention default locations for instance foldersArmin Ronacherbefore adoption9af7554
lines 337–339why, one step back337 /myapp.py338 /instance339Updated instance path documentation to explain the $PREFIX lookupArmin Ronacherbefore adoption314f920
lines 340–341why, one step back340- Uninstalled package::341Mention default locations for instance foldersArmin Ronacherbefore adoption9af7554
lines 342–344why, one step back342 /myapp343 /__init__.py344 /instanceDocumented instance rootArmin Ronacherbefore adoption187cb80
line 345why, one step back345Updated instance path documentation to explain the $PREFIX lookupArmin Ronacherbefore adoption314f920
lines 346–353why, one step back346- Installed module or package::347348 $PREFIX/lib/python2.X/site-packages/myapp349 $PREFIX/var/myapp-instance350351 ``$PREFIX`` is the prefix of your Python installation. This can be352 ``/usr`` or the path to your virtualenv. You can print the value of353 ``sys.prefix`` to see what the prefix is set to.Documented instance rootArmin Ronacherbefore adoption187cb80
lines 354–373why, one step back354355Since the config object provided loading of configuration files from356relative filenames we made it possible to change the loading via filenames357to be relative to the instance path if wanted. The behavior of relative358paths in config files can be flipped between “relative to the application359root” (the default) to “relative to instance folder” via the360`instance_relative_config` switch to the application constructor::361362 app = Flask(__name__, instance_relative_config=True)363364Here is a full example of how to configure Flask to preload the config365from a module and then override the config from a file in the config366folder if it exists::367368 app = Flask(__name__, instance_relative_config=True)369 app.config.from_object('yourapplication.default_settings')370 app.config.from_pyfile('application.cfg', silent=True)371372The path to the instance folder can be found via the373:attr:`Flask.instance_path`. Flask also provides a shortcut to open aFixed a typoArmin Ronacherbefore adoption0520425
line 374why, one step back374file from the instance folder with :meth:`Flask.open_instance_resource`.Documented instance rootArmin Ronacherbefore adoption187cb80
lines 375–377why, one step back375376Example usage for both::377Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption11c7b1d
line 378why, one step back378 filename = os.path.join(app.instance_path, 'application.cfg')Documented instance rootArmin Ronacherbefore adoption187cb80
lines 379–384why, one step back379 with open(filename) as f:380 config = f.read()381382 # or via open_instance_resource:383 with app.open_instance_resource('application.cfg') as f:384 config = f.read()