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
Provenance
- Commit
182ee31- Tree
202f550- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
78fc994
5 files changed+183 added−8 removed
modified:docs/patterns/distribute.rst+2 added
1+.. _distribute-deployment:2+3 Deploying with Distribute4 =========================5 6 `distribute`_, formerly setuptools, is an extension library that is156 unmodified linesmodified:docs/api.rst+1 added
287 unmodified lines288 Configuration289 -------------290 291 .. autoclass:: Config292+ :members:added:docs/config.rst+120 added
1+Configuration Handling2+======================3+4+.. versionadded:: 0.55+6+Applications need some kind of configuration. There are different things7+you might want to change. Like toggling debug mode, the secret key and a8+lot of very similar things.9+10+The way Flask is designed usually requires the configuration to be11+available when the application starts up. You can either hardcode the12+configuration in the code which for many small applications is not13+actually that bad, but there are better ways.14+15+Independent of how you load your config, there is a config object16+available which holds the loaded configuration values:17+The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`18+object. This is the place where Flask itself puts certain configuration19+values and also where extensions can put their configuration values. But20+this is also where you can have your own configuration.21+22+Configuration Basics23+--------------------24+25+The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and26+can be modified just like any dictionary::27+28+ app = Flask(__name__)29+ app.config['DEBUG'] = True30+31+Certain configuration values are also forwarded to the32+:attr:`~flask.Flask` object so that you can read and write them from33+there::34+35+ app.debug = True36+37+To update multiple keys at once you can use the :meth:`dict.update`38+method::39+40+ app.config.update(41+ DEBUG=True,42+ SECRET_KEY='...'43+ )44+45+Builtin Configuration Values46+----------------------------47+48+The following configuration values are used internally by Flask:49+50+=============================== =========================================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+=============================== =========================================58+59+Configuring from Files60+----------------------61+62+Configuration becomes more useful if you can configure from a file. And63+ideally that file would be outside of the actual application package that64+you can install the package with distribute (:ref:`distribute-deployment`)65+and still modify that file afterwards.66+67+So a common pattern is this::68+69+ app = Flask(__name__)70+ app.config.from_object('yourapplication.default_settings')71+ app.config.from_envvar('YOURAPPLICATION_SETTINGS')72+73+What this does is first loading the configuration from the74+`yourapplication.default_settings` module and then overrides the values75+with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`76+environment variable points to. This environment variable can be set on77+Linux or OS X with the export command in the shell before starting the78+server::79+80+ $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg81+ $ python run-app.py82+ * Running on http://127.0.0.1:5000/83+ * Restarting with reloader...84+85+On Windows systems use the `set` builtin instead::86+87+ >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg88+89+The configuration files themselves are actual Python files. Only values90+in uppercase are actually stored in the config object later on. So make91+sure to use uppercase letters for your config keys.92+93+Here an example configuration file::94+95+ DEBUG = False96+ SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'97+98+Make sure to load the configuration very early on so that extensions have99+the ability to access the configuration when starting up. There are other100+methods on the config object as well to load from individual files. For a101+complete reference, read the :class:`~flask.Config` object's102+documentation.103+104+105+Configuration Best Practices106+----------------------------107+108+The downside with the approach mentioned earlier is that it makes testing109+a little harder. There is no one 100% solution for this problem in110+general, but there are a couple of things you can do to improve that111+experience:112+113+1. 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.117+118+2. 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 lines13 quickstart14 tutorial/index15 testing16 errorhandling17+ config18 shell19 patterns/index20 deploying/index21 becomingbig23 unmodified linesmodified:flask.py+59 added-8 removed
639 unmodified lines640 641 app.config.from_pyfile('yourconfig.cfg')642 643 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::648 649 DEBUG = True650 SECRET_KEY = 'development key'651- app.config.from_module(__name__)651+ app.config.from_object(__name__)652 653 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.658 659+ Probably the most interesting way to load configurations is from an660+ environment variable pointing to a file::661+662+ app.config.from_envvar('YOURAPPLICATION_SETTINGS')663+664+ 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::667+668+ export YOURAPPLICATION_SETTINGS='/path/to/config/file'669+670+ On windows use `set` instead.671+672 :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 values2 unmodified lines678 def __init__(self, root_path, defaults=None):679 dict.__init__(self, defaults or {})680 self.root_path = root_path681 682+ 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::686+687+ app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])688+689+ :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 True704+705 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.709 710 :param filename: the filename of the config. This can either be an711 absolute filename or a filename relative to the712 root path.73 unmodified lines786 #: 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')794 795 #: 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')802 803 #: 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')808 809 #: 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')817 818 #: 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')827 828 #: the logging format used for the debug logger. This is only used when829 #: the application is in debug mode, otherwise the attached logging601 unmodified lines