Skip to content
Myr

config.rst

This file

Path

docs/config.rst

403 lines · 17.4 KiB

Last changed by

Use default send_file max-age consistently.Ron DuPlainbefore adoption26da6a5

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.  Setting a ``SERVER_NAME`` also99                                  by default enables URL generation100                                  without a request context but with an101                                  application context.102``APPLICATION_ROOT``              If the application does not occupy103                                  a whole domain or subdomain this can104                                  be set to the path where the application105                                  is configured to live.  This is for106                                  session cookie as path value.  If107                                  domains are used, this should be108                                  ``None``.109``MAX_CONTENT_LENGTH``            If set to a value in bytes, Flask will110                                  reject incoming requests with a111                                  content length greater than this by112                                  returning a 413 status code.113``SEND_FILE_MAX_AGE_DEFAULT``:    Default cache control max age to use with114                                  :meth:`~flask.Flask.send_static_file` (the115                                  default static file handler) and116                                  :func:`~flask.send_file`, in117                                  seconds. Override this value on a per-file118                                  basis using the119                                  :meth:`~flask.Flask.get_send_file_max_age`120                                  hook on :class:`~flask.Flask` or121                                  :class:`~flask.Blueprint`,122                                  respectively. Defaults to 43200 (12 hours).123``TRAP_HTTP_EXCEPTIONS``          If this is set to ``True`` Flask will124                                  not execute the error handlers of HTTP125                                  exceptions but instead treat the126                                  exception like any other and bubble it127                                  through the exception stack.  This is128                                  helpful for hairy debugging situations129                                  where you have to find out where an HTTP130                                  exception is coming from.131``TRAP_BAD_REQUEST_ERRORS``       Werkzeug's internal data structures that132                                  deal with request specific data will133                                  raise special key errors that are also134                                  bad request exceptions.  Likewise many135                                  operations can implicitly fail with a136                                  BadRequest exception for consistency.137                                  Since it's nice for debugging to know138                                  why exactly it failed this flag can be139                                  used to debug those situations.  If this140                                  config is set to ``True`` you will get141                                  a regular traceback instead.142``PREFERRED_URL_SCHEME``          The URL scheme that should be used for143                                  URL generation if no URL scheme is144                                  available.  This defaults to ``http``.145================================= =========================================146147.. admonition:: More on ``SERVER_NAME``148149   The ``SERVER_NAME`` key is used for the subdomain support.  Because150   Flask cannot guess the subdomain part without the knowledge of the151   actual server name, this is required if you want to work with152   subdomains.  This is also used for the session cookie.153154   Please keep in mind that not only Flask has the problem of not knowing155   what subdomains are, your web browser does as well.  Most modern web156   browsers will not allow cross-subdomain cookies to be set on a157   server name without dots in it.  So if your server name is158   ``'localhost'`` you will not be able to set a cookie for159   ``'localhost'`` and every subdomain of it.  Please chose a different160   server name in that case, like ``'myapplication.local'`` and add161   this name + the subdomains you want to use into your host config162   or setup a local `bind`_.163164.. _bind: https://www.isc.org/software/bind165166.. versionadded:: 0.4167   ``LOGGER_NAME``168169.. versionadded:: 0.5170   ``SERVER_NAME``171172.. versionadded:: 0.6173   ``MAX_CONTENT_LENGTH``174175.. versionadded:: 0.7176   ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``177178.. versionadded:: 0.8179   ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,180   ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,181   ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,182   ``SESSION_COOKIE_SECURE``183184.. versionadded:: 0.9185   ``PREFERRED_URL_SCHEME``186187Configuring from Files188----------------------189190Configuration becomes more useful if you can store it in a separate file,191ideally located outside the actual application package. This makes192packaging and distributing your application possible via various package193handling tools (:ref:`distribute-deployment`) and finally modifying the194configuration file afterwards.195196So a common pattern is this::197198    app = Flask(__name__)199    app.config.from_object('yourapplication.default_settings')200    app.config.from_envvar('YOURAPPLICATION_SETTINGS')201202This first loads the configuration from the203`yourapplication.default_settings` module and then overrides the values204with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`205environment variable points to.  This environment variable can be set on206Linux or OS X with the export command in the shell before starting the207server::208209    $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg210    $ python run-app.py211     * Running on http://127.0.0.1:5000/212     * Restarting with reloader...213214On Windows systems use the `set` builtin instead::215216    >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg217218The configuration files themselves are actual Python files.  Only values219in uppercase are actually stored in the config object later on.  So make220sure to use uppercase letters for your config keys.221222Here is an example of a configuration file::223224    # Example configuration225    DEBUG = False226    SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'227228Make sure to load the configuration very early on, so that extensions have229the ability to access the configuration when starting up.  There are other230methods on the config object as well to load from individual files.  For a231complete reference, read the :class:`~flask.Config` object's232documentation.233234235Configuration Best Practices236----------------------------237238The downside with the approach mentioned earlier is that it makes testing239a little harder.  There is no single 100% solution for this problem in240general, but there are a couple of things you can keep in mind to improve241that experience:2422431.  create your application in a function and register blueprints on it.244    That way you can create multiple instances of your application with245    different configurations attached which makes unittesting a lot246    easier.  You can use this to pass in configuration as needed.2472482.  Do not write code that needs the configuration at import time.  If you249    limit yourself to request-only accesses to the configuration you can250    reconfigure the object later on as needed.251252253Development / Production254------------------------255256Most applications need more than one configuration.  There should be at257least separate configurations for the production server and the one used258during development.  The easiest way to handle this is to use a default259configuration that is always loaded and part of the version control, and a260separate configuration that overrides the values as necessary as mentioned261in the example above::262263    app = Flask(__name__)264    app.config.from_object('yourapplication.default_settings')265    app.config.from_envvar('YOURAPPLICATION_SETTINGS')266267Then you just have to add a separate `config.py` file and export268``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done.  However269there are alternative ways as well.  For example you could use imports or270subclassing.271272What is very popular in the Django world is to make the import explicit in273the config file by adding an ``from yourapplication.default_settings274import *`` to the top of the file and then overriding the changes by hand.275You could also inspect an environment variable like276``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc277and import different hardcoded files based on that.278279An interesting pattern is also to use classes and inheritance for280configuration::281282    class Config(object):283        DEBUG = False284        TESTING = False285        DATABASE_URI = 'sqlite://:memory:'286287    class ProductionConfig(Config):288        DATABASE_URI = 'mysql://user@localhost/foo'289290    class DevelopmentConfig(Config):291        DEBUG = True292293    class TestingConfig(Config):294        TESTING = True295296To enable such a config you just have to call into297:meth:`~flask.Config.from_object`::298299    app.config.from_object('configmodule.ProductionConfig')300301There are many different ways and it's up to you how you want to manage302your configuration files.  However here a list of good recommendations:303304-   keep a default configuration in version control.  Either populate the305    config with this default configuration or import it in your own306    configuration files before overriding values.307-   use an environment variable to switch between the configurations.308    This can be done from outside the Python interpreter and makes309    development and deployment much easier because you can quickly and310    easily switch between different configs without having to touch the311    code at all.  If you are working often on different projects you can312    even create your own script for sourcing that activates a virtualenv313    and exports the development configuration for you.314-   Use a tool like `fabric`_ in production to push code and315    configurations separately to the production server(s).  For some316    details about how to do that, head over to the317    :ref:`fabric-deployment` pattern.318319.. _fabric: http://fabfile.org/320321322.. _instance-folders:323324Instance Folders325----------------326327.. versionadded:: 0.8328329Flask 0.8 introduces instance folders.  Flask for a long time made it330possible to refer to paths relative to the application's folder directly331(via :attr:`Flask.root_path`).  This was also how many developers loaded332configurations stored next to the application.  Unfortunately however this333only works well if applications are not packages in which case the root334path refers to the contents of the package.335336With Flask 0.8 a new attribute was introduced:337:attr:`Flask.instance_path`.  It refers to a new concept called the338“instance folder”.  The instance folder is designed to not be under339version control and be deployment specific.  It's the perfect place to340drop things that either change at runtime or configuration files.341342You can either explicitly provide the path of the instance folder when343creating the Flask application or you can let Flask autodetect the344instance folder.  For explicit configuration use the `instance_path`345parameter::346347    app = Flask(__name__, instance_path='/path/to/instance/folder')348349Please keep in mind that this path *must* be absolute when provided.350351If the `instance_path` parameter is not provided the following default352locations are used:353354-   Uninstalled module::355356        /myapp.py357        /instance358359-   Uninstalled package::360361        /myapp362            /__init__.py363        /instance364365-   Installed module or package::366367        $PREFIX/lib/python2.X/site-packages/myapp368        $PREFIX/var/myapp-instance369370    ``$PREFIX`` is the prefix of your Python installation.  This can be371    ``/usr`` or the path to your virtualenv.  You can print the value of372    ``sys.prefix`` to see what the prefix is set to.373374Since the config object provided loading of configuration files from375relative filenames we made it possible to change the loading via filenames376to be relative to the instance path if wanted.  The behavior of relative377paths in config files can be flipped between “relative to the application378root” (the default) to “relative to instance folder” via the379`instance_relative_config` switch to the application constructor::380381    app = Flask(__name__, instance_relative_config=True)382383Here is a full example of how to configure Flask to preload the config384from a module and then override the config from a file in the config385folder if it exists::386387    app = Flask(__name__, instance_relative_config=True)388    app.config.from_object('yourapplication.default_settings')389    app.config.from_pyfile('application.cfg', silent=True)390391The path to the instance folder can be found via the392:attr:`Flask.instance_path`.  Flask also provides a shortcut to open a393file from the instance folder with :meth:`Flask.open_instance_resource`.394395Example usage for both::396397    filename = os.path.join(app.instance_path, 'application.cfg')398    with open(filename) as f:399        config = f.read()400401    # or via open_instance_resource:402    with app.open_instance_resource('application.cfg') as f:403        config = f.read()