Skip to content
Myr

Added chapter about config

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 78fc994 · Browse files · 5 files+183 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+183 added−8 removed

  • other:+183 added−8 removed

5 files+183 added−8 removed

modified:docs/patterns/distribute.rst+2 added
1.. _distribute-deployment:23Deploying with Distribute4=========================56`distribute`_, formerly setuptools, is an extension library that is
156 unmodified lines
modified:docs/api.rst+1 added
287 unmodified lines
288Configuration289-------------290291.. autoclass:: Config292 :members:
added:docs/config.rst+120 added
1Configuration Handling2======================34.. versionadded:: 0.556Applications need some kind of configuration. There are different things7you might want to change. Like toggling debug mode, the secret key and a8lot of very similar things.910The way Flask is designed usually requires the configuration to be11available when the application starts up. You can either hardcode the12configuration in the code which for many small applications is not13actually that bad, but there are better ways.1415Independent of how you load your config, there is a config object16available which holds the loaded configuration values:17The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`18object. This is the place where Flask itself puts certain configuration19values and also where extensions can put their configuration values. But20this is also where you can have your own configuration.2122Configuration Basics23--------------------2425The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and26can be modified just like any dictionary::2728 app = Flask(__name__)29 app.config['DEBUG'] = True3031Certain configuration values are also forwarded to the32:attr:`~flask.Flask` object so that you can read and write them from33there::3435 app.debug = True3637To update multiple keys at once you can use the :meth:`dict.update`38method::3940 app.config.update(41 DEBUG=True,42 SECRET_KEY='...'43 )4445Builtin Configuration Values46----------------------------4748The following configuration values are used internally by Flask:4950=============================== =========================================51``DEBUG`` enable/disable debug mode52``SECRET_KEY`` the secret key53``SESSION_COOKIE_NAME`` the name of the session cookie54``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as55 :class:`datetime.timedelta` object.56``USE_X_SENDFILE`` enable/disable x-sendfile57=============================== =========================================5859Configuring from Files60----------------------6162Configuration becomes more useful if you can configure from a file. And63ideally that file would be outside of the actual application package that64you can install the package with distribute (:ref:`distribute-deployment`)65and still modify that file afterwards.6667So a common pattern is this::6869 app = Flask(__name__)70 app.config.from_object('yourapplication.default_settings')71 app.config.from_envvar('YOURAPPLICATION_SETTINGS')7273What this does is first loading the configuration from the74`yourapplication.default_settings` module and then overrides the values75with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`76environment variable points to. This environment variable can be set on77Linux or OS X with the export command in the shell before starting the78server::7980 $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg81 $ python run-app.py82 * Running on http://127.0.0.1:5000/83 * Restarting with reloader...8485On Windows systems use the `set` builtin instead::8687 >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg8889The configuration files themselves are actual Python files. Only values90in uppercase are actually stored in the config object later on. So make91sure to use uppercase letters for your config keys.9293Here an example configuration file::9495 DEBUG = False96 SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'9798Make sure to load the configuration very early on so that extensions have99the ability to access the configuration when starting up. There are other100methods on the config object as well to load from individual files. For a101complete reference, read the :class:`~flask.Config` object's102documentation.103104105Configuration Best Practices106----------------------------107108The downside with the approach mentioned earlier is that it makes testing109a little harder. There is no one 100% solution for this problem in110general, but there are a couple of things you can do to improve that111experience:1121131. create your application in a function and register modules on it.114 That way you can create multiple instances of your application with115 different configurations attached which makes unittesting a lot116 easier. You can use this to pass in configuration as needed.1171182. Do not write code that needs the configuration at import time. If you119 limit yourself to request-only accesses to the configuration you can120 reconfigure the object later on as needed.
modified:docs/contents.rst.inc+1 added
12 unmodified lines
13 quickstart14 tutorial/index15 testing16 errorhandling17 config18 shell19 patterns/index20 deploying/index21 becomingbig
23 unmodified lines
modified:flask.py+59 added-8 removed
639 unmodified lines
640641 app.config.from_pyfile('yourconfig.cfg')642643 Or alternatively you can define the configuration options in the644 module that calls :meth:`from_module` or provide an import path to644 module that calls :meth:`from_object` or provide an import path to645 a module that should be loaded. It is also possible to tell it to646 use the same module and with that provide the configuration values647 just before the call::648649 DEBUG = True650 SECRET_KEY = 'development key'651 app.config.from_module(__name__)651 app.config.from_object(__name__)652653 In both cases (loading from any Python file or loading from modules),654 only uppercase keys are added to the config. The actual keys in the655 config are however lowercased so they are converted for you. This makes656 it possible to use lowercase values in the config file for temporary657 values that are not added to the config or to define the config keys in658 the same file that implements the application.654 only uppercase keys are added to the config. This makes it possible to use655 lowercase values in the config file for temporary values that are not added656 to the config or to define the config keys in the same file that implements657 the application.658659 Probably the most interesting way to load configurations is from an660 environment variable pointing to a file::661662 app.config.from_envvar('YOURAPPLICATION_SETTINGS')663664 In this case before launching the application you have to set this665 environment variable to the file you want to use. On Linux and OS X666 use the export statement::667668 export YOURAPPLICATION_SETTINGS='/path/to/config/file'669670 On windows use `set` instead.671672 :param root_path: path to which files are read relative from. When the673 config object is created by the application, this is674 the application's :attr:`~flask.Flask.root_path`.675 :param defaults: an optional dictionary of default values
2 unmodified lines
678 def __init__(self, root_path, defaults=None):679 dict.__init__(self, defaults or {})680 self.root_path = root_path681682 def from_envvar(self, variable_name, silent=False):683 """Loads a configuration from an environment variable pointing to684 a configuration file. This basically is just a shortcut with nicer685 error messages for this line of code::686687 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])688689 :param variable_name: name of the environment variable690 :param silent: set to `True` if you want silent failing for missing691 files.692 :return: bool. `True` if able to load config, `False` otherwise.693 """694 rv = os.environ.get(variable_name)695 if not rv:696 if silent:697 return False698 raise RuntimeError('The environment variable %r is not set '699 'and as such configuration could not be '700 'loaded. Set this variable and make it '701 'point to a configuration file')702 self.from_pyfile(rv)703 return True704705 def from_pyfile(self, filename):706 """Updates the values in the config from a Python file. This function707 behaves as if the file was imported as module with the673 :meth:`from_module` function.708 :meth:`from_object` function.709710 :param filename: the filename of the config. This can either be an711 absolute filename or a filename relative to the712 root path.
73 unmodified lines
786 #: the debug flag. Set this to `True` to enable debugging of the787 #: application. In debug mode the debugger will kick in when an unhandled788 #: exception ocurrs and the integrated server will automatically reload789 #: the application if changes in the code are detected.790 #:791 #: This attribute can also be configured from the config with the `DEBUG`792 #: configuration key. Defaults to `False`.793 debug = ConfigAttribute('DEBUG')794795 #: if a secret key is set, cryptographic components can use this to796 #: sign cookies and other things. Set this to a complex random value797 #: when you want to use the secure cookie for instance.798 #:799 #: This attribute can also be configured from the config with the800 #: `SECRET_KEY` configuration key. Defaults to `None`.801 secret_key = ConfigAttribute('SECRET_KEY')802803 #: The secure cookie uses this for the name of the session cookie804 #:805 #: This attribute can also be configured from the config with the806 #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``807 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')808809 #: A :class:`~datetime.timedelta` which is used to set the expiration810 #: date of a permanent session. The default is 31 days which makes a811 #: permanent session survive for roughly one month.812 #:813 #: This attribute can also be configured from the config with the814 #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to815 #: ``timedelta(days=31)``816 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME')817818 #: Enable this if you want to use the X-Sendfile feature. Keep in819 #: mind that the server has to support this. This only affects files820 #: sent with the :func:`send_file` method.821 #:822 #: .. versionadded:: 0.2823 #:824 #: This attribute can also be configured from the config with the825 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.826 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')827828 #: the logging format used for the debug logger. This is only used when829 #: the application is in debug mode, otherwise the attached logging
601 unmodified lines