Skip to content
Myr

config.rst

This file

Path

docs/config.rst

441 lines · 19.8 KiB

Last changed by

Merge pull request #935 from markhildreth/doc-fixArmin Ronacherbefore adoption1bddb30

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``SESSION_REFRESH_EACH_REQUEST``  this flag controls how permanent92                                  sessions are refreshed.  If set to `True`93                                  (which is the default) then the cookie94                                  is refreshed each request which95                                  automatically bumps the lifetime.  If96                                  set to `False` a `set-cookie` header is97                                  only sent if the session is modified.98                                  Non permanent sessions are not affected99                                  by this.100``USE_X_SENDFILE``                enable/disable x-sendfile101``LOGGER_NAME``                   the name of the logger102``SERVER_NAME``                   the name and port number of the server.103                                  Required for subdomain support (e.g.:104                                  ``'myapp.dev:5000'``)  Note that105                                  localhost does not support subdomains so106                                  setting this to “localhost” does not107                                  help.  Setting a ``SERVER_NAME`` also108                                  by default enables URL generation109                                  without a request context but with an110                                  application context.111``APPLICATION_ROOT``              If the application does not occupy112                                  a whole domain or subdomain this can113                                  be set to the path where the application114                                  is configured to live.  This is for115                                  session cookie as path value.  If116                                  domains are used, this should be117                                  ``None``.118``MAX_CONTENT_LENGTH``            If set to a value in bytes, Flask will119                                  reject incoming requests with a120                                  content length greater than this by121                                  returning a 413 status code.122``SEND_FILE_MAX_AGE_DEFAULT``:    Default cache control max age to use with123                                  :meth:`~flask.Flask.send_static_file` (the124                                  default static file handler) and125                                  :func:`~flask.send_file`, in126                                  seconds. Override this value on a per-file127                                  basis using the128                                  :meth:`~flask.Flask.get_send_file_max_age`129                                  hook on :class:`~flask.Flask` or130                                  :class:`~flask.Blueprint`,131                                  respectively. Defaults to 43200 (12 hours).132``TRAP_HTTP_EXCEPTIONS``          If this is set to ``True`` Flask will133                                  not execute the error handlers of HTTP134                                  exceptions but instead treat the135                                  exception like any other and bubble it136                                  through the exception stack.  This is137                                  helpful for hairy debugging situations138                                  where you have to find out where an HTTP139                                  exception is coming from.140``TRAP_BAD_REQUEST_ERRORS``       Werkzeug's internal data structures that141                                  deal with request specific data will142                                  raise special key errors that are also143                                  bad request exceptions.  Likewise many144                                  operations can implicitly fail with a145                                  BadRequest exception for consistency.146                                  Since it's nice for debugging to know147                                  why exactly it failed this flag can be148                                  used to debug those situations.  If this149                                  config is set to ``True`` you will get150                                  a regular traceback instead.151``PREFERRED_URL_SCHEME``          The URL scheme that should be used for152                                  URL generation if no URL scheme is153                                  available.  This defaults to ``http``.154``JSON_AS_ASCII``                 By default Flask serialize object to155                                  ascii-encoded JSON.  If this is set to156                                  ``False`` Flask will not encode to ASCII157                                  and output strings as-is and return158                                  unicode strings.  ``jsonfiy`` will159                                  automatically encode it in ``utf-8``160                                  then for transport for instance.161``JSON_SORT_KEYS``                By default Flask will serialize JSON162                                  objects in a way that the keys are163                                  ordered.  This is done in order to164                                  ensure that independent of the hash seed165                                  of the dictionary the return value will166                                  be consistent to not trash external HTTP167                                  caches.  You can override the default168                                  behavior by changing this variable.169                                  This is not recommended but might give170                                  you a performance improvement on the171                                  cost of cachability.172``JSONIFY_PRETTYPRINT_REGULAR``   If this is set to ``True`` (the default)173                                  jsonify responses will be pretty printed174                                  if they are not requested by an175                                  XMLHttpRequest object (controlled by176                                  the ``X-Requested-With`` header)177================================= =========================================178179.. admonition:: More on ``SERVER_NAME``180181   The ``SERVER_NAME`` key is used for the subdomain support.  Because182   Flask cannot guess the subdomain part without the knowledge of the183   actual server name, this is required if you want to work with184   subdomains.  This is also used for the session cookie.185186   Please keep in mind that not only Flask has the problem of not knowing187   what subdomains are, your web browser does as well.  Most modern web188   browsers will not allow cross-subdomain cookies to be set on a189   server name without dots in it.  So if your server name is190   ``'localhost'`` you will not be able to set a cookie for191   ``'localhost'`` and every subdomain of it.  Please chose a different192   server name in that case, like ``'myapplication.local'`` and add193   this name + the subdomains you want to use into your host config194   or setup a local `bind`_.195196.. _bind: https://www.isc.org/software/bind197198.. versionadded:: 0.4199   ``LOGGER_NAME``200201.. versionadded:: 0.5202   ``SERVER_NAME``203204.. versionadded:: 0.6205   ``MAX_CONTENT_LENGTH``206207.. versionadded:: 0.7208   ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``209210.. versionadded:: 0.8211   ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,212   ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,213   ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,214   ``SESSION_COOKIE_SECURE``215216.. versionadded:: 0.9217   ``PREFERRED_URL_SCHEME``218219.. versionadded:: 0.10220   ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``221222.. versionadded:: 1.0223   ``SESSION_REFRESH_EACH_REQUEST``224225Configuring from Files226----------------------227228Configuration becomes more useful if you can store it in a separate file,229ideally located outside the actual application package. This makes230packaging and distributing your application possible via various package231handling tools (:ref:`distribute-deployment`) and finally modifying the232configuration file afterwards.233234So a common pattern is this::235236    app = Flask(__name__)237    app.config.from_object('yourapplication.default_settings')238    app.config.from_envvar('YOURAPPLICATION_SETTINGS')239240This first loads the configuration from the241`yourapplication.default_settings` module and then overrides the values242with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`243environment variable points to.  This environment variable can be set on244Linux or OS X with the export command in the shell before starting the245server::246247    $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg248    $ python run-app.py249     * Running on http://127.0.0.1:5000/250     * Restarting with reloader...251252On Windows systems use the `set` builtin instead::253254    >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg255256The configuration files themselves are actual Python files.  Only values257in uppercase are actually stored in the config object later on.  So make258sure to use uppercase letters for your config keys.259260Here is an example of a configuration file::261262    # Example configuration263    DEBUG = False264    SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'265266Make sure to load the configuration very early on, so that extensions have267the ability to access the configuration when starting up.  There are other268methods on the config object as well to load from individual files.  For a269complete reference, read the :class:`~flask.Config` object's270documentation.271272273Configuration Best Practices274----------------------------275276The downside with the approach mentioned earlier is that it makes testing277a little harder.  There is no single 100% solution for this problem in278general, but there are a couple of things you can keep in mind to improve279that experience:2802811.  create your application in a function and register blueprints on it.282    That way you can create multiple instances of your application with283    different configurations attached which makes unittesting a lot284    easier.  You can use this to pass in configuration as needed.2852862.  Do not write code that needs the configuration at import time.  If you287    limit yourself to request-only accesses to the configuration you can288    reconfigure the object later on as needed.289290291Development / Production292------------------------293294Most applications need more than one configuration.  There should be at295least separate configurations for the production server and the one used296during development.  The easiest way to handle this is to use a default297configuration that is always loaded and part of the version control, and a298separate configuration that overrides the values as necessary as mentioned299in the example above::300301    app = Flask(__name__)302    app.config.from_object('yourapplication.default_settings')303    app.config.from_envvar('YOURAPPLICATION_SETTINGS')304305Then you just have to add a separate `config.py` file and export306``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done.  However307there are alternative ways as well.  For example you could use imports or308subclassing.309310What is very popular in the Django world is to make the import explicit in311the config file by adding an ``from yourapplication.default_settings312import *`` to the top of the file and then overriding the changes by hand.313You could also inspect an environment variable like314``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc315and import different hardcoded files based on that.316317An interesting pattern is also to use classes and inheritance for318configuration::319320    class Config(object):321        DEBUG = False322        TESTING = False323        DATABASE_URI = 'sqlite://:memory:'324325    class ProductionConfig(Config):326        DATABASE_URI = 'mysql://user@localhost/foo'327328    class DevelopmentConfig(Config):329        DEBUG = True330331    class TestingConfig(Config):332        TESTING = True333334To enable such a config you just have to call into335:meth:`~flask.Config.from_object`::336337    app.config.from_object('configmodule.ProductionConfig')338339There are many different ways and it's up to you how you want to manage340your configuration files.  However here a list of good recommendations:341342-   keep a default configuration in version control.  Either populate the343    config with this default configuration or import it in your own344    configuration files before overriding values.345-   use an environment variable to switch between the configurations.346    This can be done from outside the Python interpreter and makes347    development and deployment much easier because you can quickly and348    easily switch between different configs without having to touch the349    code at all.  If you are working often on different projects you can350    even create your own script for sourcing that activates a virtualenv351    and exports the development configuration for you.352-   Use a tool like `fabric`_ in production to push code and353    configurations separately to the production server(s).  For some354    details about how to do that, head over to the355    :ref:`fabric-deployment` pattern.356357.. _fabric: http://fabfile.org/358359360.. _instance-folders:361362Instance Folders363----------------364365.. versionadded:: 0.8366367Flask 0.8 introduces instance folders.  Flask for a long time made it368possible to refer to paths relative to the application's folder directly369(via :attr:`Flask.root_path`).  This was also how many developers loaded370configurations stored next to the application.  Unfortunately however this371only works well if applications are not packages in which case the root372path refers to the contents of the package.373374With Flask 0.8 a new attribute was introduced:375:attr:`Flask.instance_path`.  It refers to a new concept called the376“instance folder”.  The instance folder is designed to not be under377version control and be deployment specific.  It's the perfect place to378drop things that either change at runtime or configuration files.379380You can either explicitly provide the path of the instance folder when381creating the Flask application or you can let Flask autodetect the382instance folder.  For explicit configuration use the `instance_path`383parameter::384385    app = Flask(__name__, instance_path='/path/to/instance/folder')386387Please keep in mind that this path *must* be absolute when provided.388389If the `instance_path` parameter is not provided the following default390locations are used:391392-   Uninstalled module::393394        /myapp.py395        /instance396397-   Uninstalled package::398399        /myapp400            /__init__.py401        /instance402403-   Installed module or package::404405        $PREFIX/lib/python2.X/site-packages/myapp406        $PREFIX/var/myapp-instance407408    ``$PREFIX`` is the prefix of your Python installation.  This can be409    ``/usr`` or the path to your virtualenv.  You can print the value of410    ``sys.prefix`` to see what the prefix is set to.411412Since the config object provided loading of configuration files from413relative filenames we made it possible to change the loading via filenames414to be relative to the instance path if wanted.  The behavior of relative415paths in config files can be flipped between “relative to the application416root” (the default) to “relative to instance folder” via the417`instance_relative_config` switch to the application constructor::418419    app = Flask(__name__, instance_relative_config=True)420421Here is a full example of how to configure Flask to preload the config422from a module and then override the config from a file in the config423folder if it exists::424425    app = Flask(__name__, instance_relative_config=True)426    app.config.from_object('yourapplication.default_settings')427    app.config.from_pyfile('application.cfg', silent=True)428429The path to the instance folder can be found via the430:attr:`Flask.instance_path`.  Flask also provides a shortcut to open a431file from the instance folder with :meth:`Flask.open_instance_resource`.432433Example usage for both::434435    filename = os.path.join(app.instance_path, 'application.cfg')436    with open(filename) as f:437        config = f.read()438439    # or via open_instance_resource:440    with app.open_instance_resource('application.cfg') as f:441        config = f.read()