Skip to content
Myr

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 file

Take it

1.. _config:23Configuration Handling4======================56.. versionadded:: 0.378Applications 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.1213The 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 the35:attr:`~flask.Flask` object so you can read and write them from there::3637    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 cookie73``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`.87``PERMANENT_SESSION_LIFETIME``    the lifetime of a permanent session as88                                  :class:`datetime.timedelta` object.89                                  Starting with Flask 0.8 this can also be90                                  an integer representing seconds.91``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.:95                                  ``'myapp.dev:5000'``)  Note that96                                  localhost does not support subdomains so97                                  setting this to “localhost” does not98                                  help.99``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``.106``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.110``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.118``TRAP_BAD_REQUEST_ERRORS``       Werkzeug's internal data structures that119                                  deal with request specific data will120                                  raise special key errors that are also121                                  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 this127                                  config is set to ``True`` you will get128                                  a regular traceback instead.129================================= =========================================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``161162.. versionadded:: 0.8163   ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,164   ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,165   ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,166   ``SESSION_COOKIE_SECURE``167168Configuring from Files169----------------------170171Configuration 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.176177So 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.202203Here is an example of a configuration file::204205    # Example configuration206    DEBUG = False207    SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'208209Make sure to load the configuration very early on, so that extensions have210the 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 testing220a 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:2232241.  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------------------------236237Most 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 a241separate 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/301302303.. _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.322323You 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::327328    app = Flask(__name__, instance_path='/path/to/instance/folder')329330Please keep in mind that this path *must* be absolute when provided.331332If the `instance_path` parameter is not provided the following default333locations are used:334335-   Uninstalled module::336337        /myapp.py338        /instance339340-   Uninstalled package::341342        /myapp343            /__init__.py344        /instance345346-   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.354355Since 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 a374file from the instance folder with :meth:`Flask.open_instance_resource`.375376Example usage for both::377378    filename = os.path.join(app.instance_path, 'application.cfg')379    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()