Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 246 lines (188 sloc) 10.079 kB
dfecc86 @mitsuhiko Ported examples over to new config. documented upgrading
authored
1 .. _config:
2
182ee31 @mitsuhiko Added chapter about config
authored
3 Configuration Handling
4 ======================
5
ce6e4cb @mitsuhiko 0.5 is 0.3 now, why skip numbers?
authored
6 .. versionadded:: 0.3
182ee31 @mitsuhiko Added chapter about config
authored
7
8 Applications need some kind of configuration. There are different things
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
9 you might want to change like toggling debug mode, the secret key, and a
182ee31 @mitsuhiko Added chapter about config
authored
10 lot of very similar things.
11
12 The way Flask is designed usually requires the configuration to be
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
13 available when the application starts up. You can hardcode the
14 configuration in the code, which for many small applications is not
182ee31 @mitsuhiko Added chapter about config
authored
15 actually that bad, but there are better ways.
16
17 Independent of how you load your config, there is a config object
18 available which holds the loaded configuration values:
19 The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`
20 object. This is the place where Flask itself puts certain configuration
21 values and also where extensions can put their configuration values. But
22 this is also where you can have your own configuration.
23
24 Configuration Basics
25 --------------------
26
27 The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and
28 can be modified just like any dictionary::
29
30 app = Flask(__name__)
31 app.config['DEBUG'] = True
32
33 Certain configuration values are also forwarded to the
34 :attr:`~flask.Flask` object so that you can read and write them from
35 there::
36
37 app.debug = True
38
39 To update multiple keys at once you can use the :meth:`dict.update`
40 method::
41
42 app.config.update(
43 DEBUG=True,
44 SECRET_KEY='...'
45 )
46
47 Builtin Configuration Values
48 ----------------------------
49
50 The following configuration values are used internally by Flask:
51
dfecc86 @mitsuhiko Ported examples over to new config. documented upgrading
authored
52 .. tabularcolumns:: |p{6.5cm}|p{8.5cm}|
53
e71a5ff @mitsuhiko Started work on new request dispatching. Unittests not yet updated
authored
54 ================================= =========================================
55 ``DEBUG`` enable/disable debug mode
56 ``TESTING`` enable/disable testing mode
57 ``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the
58 propagation of exceptions. If not set or
59 explicitly set to `None` this is
60 implicitly true if either `TESTING` or
61 `DEBUG` is true.
62 ``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in
63 debug mode the request context is not
64 popped on exceptions to enable debuggers
65 to introspect the data. This can be
66 disabled by this key. You can also use
67 this setting to force-enable it for non
68 debug execution which might be useful to
69 debug production applications (but also
70 very risky).
71 ``SECRET_KEY`` the secret key
72 ``SESSION_COOKIE_NAME`` the name of the session cookie
73 ``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as
74 :class:`datetime.timedelta` object.
75 ``USE_X_SENDFILE`` enable/disable x-sendfile
76 ``LOGGER_NAME`` the name of the logger
77 ``SERVER_NAME`` the name of the server. Required for
78 subdomain support (e.g.: ``'localhost'``)
79 ``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will
80 reject incoming requests with a
81 content length greater than this by
82 returning a 413 status code.
83 ================================= =========================================
182ee31 @mitsuhiko Added chapter about config
authored
84
f8f8463 @mitsuhiko Documented cookie problem for #80
authored
85 .. admonition:: More on ``SERVER_NAME``
86
87 The ``SERVER_NAME`` key is used for the subdomain support. Because
88 Flask cannot guess the subdomain part without the knowledge of the
89 actual server name, this is required if you want to work with
90 subdomains. This is also used for the session cookie.
91
92 Please keep in mind that not only Flask has the problem of not knowing
93 what subdomains are, your web browser does as well. Most modern web
94 browsers will not allow cross-subdomain cookies to be set on a
95 server name without dots in it. So if your server name is
96 ``'localhost'`` you will not be able to set a cookie for
97 ``'localhost'`` and every subdomain of it. Please chose a different
98 server name in that case, like ``'myapplication.local'`` and add
99 this name + the subdomains you want to use into your host config
100 or setup a local `bind`_.
101
102 .. _bind: https://www.isc.org/software/bind
103
f195d92 @mitsuhiko Added proper subdomain support
authored
104 .. versionadded:: 0.4
105 ``LOGGER_NAME``
106
107 .. versionadded:: 0.5
108 ``SERVER_NAME``
109
dbb3620 @mitsuhiko Fixed an rst error
authored
110 .. versionadded:: 0.6
111 ``MAX_CONTENT_LENGTH``
b1790cc @mitsuhiko Added MAX_CONTENT_LENGTH config key
authored
112
8569dfe @mitsuhiko Added a PROPAGATE_EXCEPTIONS flag
authored
113 .. versionadded:: 0.7
e71a5ff @mitsuhiko Started work on new request dispatching. Unittests not yet updated
authored
114 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``
8569dfe @mitsuhiko Added a PROPAGATE_EXCEPTIONS flag
authored
115
182ee31 @mitsuhiko Added chapter about config
authored
116 Configuring from Files
117 ----------------------
118
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
119 Configuration becomes more useful if you can configure from a file, and
120 ideally that file would be outside of the actual application package so that
182ee31 @mitsuhiko Added chapter about config
authored
121 you can install the package with distribute (:ref:`distribute-deployment`)
122 and still modify that file afterwards.
123
124 So a common pattern is this::
125
126 app = Flask(__name__)
127 app.config.from_object('yourapplication.default_settings')
128 app.config.from_envvar('YOURAPPLICATION_SETTINGS')
129
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
130 This first loads the configuration from the
182ee31 @mitsuhiko Added chapter about config
authored
131 `yourapplication.default_settings` module and then overrides the values
132 with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`
133 environment variable points to. This environment variable can be set on
134 Linux or OS X with the export command in the shell before starting the
135 server::
136
137 $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
138 $ python run-app.py
139 * Running on http://127.0.0.1:5000/
140 * Restarting with reloader...
141
142 On Windows systems use the `set` builtin instead::
143
144 >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
145
146 The configuration files themselves are actual Python files. Only values
147 in uppercase are actually stored in the config object later on. So make
148 sure to use uppercase letters for your config keys.
149
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
150 Here is an example configuration file::
182ee31 @mitsuhiko Added chapter about config
authored
151
152 DEBUG = False
153 SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'
154
155 Make sure to load the configuration very early on so that extensions have
156 the ability to access the configuration when starting up. There are other
157 methods on the config object as well to load from individual files. For a
158 complete reference, read the :class:`~flask.Config` object's
159 documentation.
160
161
162 Configuration Best Practices
163 ----------------------------
164
165 The downside with the approach mentioned earlier is that it makes testing
166 a little harder. There is no one 100% solution for this problem in
167 general, but there are a couple of things you can do to improve that
168 experience:
169
170 1. create your application in a function and register modules on it.
171 That way you can create multiple instances of your application with
172 different configurations attached which makes unittesting a lot
173 easier. You can use this to pass in configuration as needed.
174
175 2. Do not write code that needs the configuration at import time. If you
176 limit yourself to request-only accesses to the configuration you can
177 reconfigure the object later on as needed.
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
178
179
180 Development / Production
181 ------------------------
182
183 Most applications need more than one configuration. There will at least
184 be a separate configuration for a production server and one used during
185 development. The easiest way to handle this is to use a default
186 configuration that is always loaded and part of version control, and a
187 separate configuration that overrides the values as necessary as mentioned
188 in the example above::
189
190 app = Flask(__name__)
191 app.config.from_object('yourapplication.default_settings')
192 app.config.from_envvar('YOURAPPLICATION_SETTINGS')
193
194 Then you just have to add a separate `config.py` file and export
195 ``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However
196 there are alternative ways as well. For example you could use imports or
197 subclassing.
198
199 What is very popular in the Django world is to make the import explicit in
200 the config file by adding an ``from yourapplication.default_settings
201 import *`` to the top of the file and then overriding the changes by hand.
202 You could also inspect an environment variable like
203 ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc
204 and import different hardcoded files based on that.
205
206 An interesting pattern is also to use classes and inheritance for
207 configuration::
208
209 class Config(object):
210 DEBUG = False
211 TESTING = False
212 DATABASE_URI = 'sqlite://:memory:'
213
214 class ProductionConfig(Config):
215 DATABASE_URI = 'mysql://user@localhost/foo'
216
217 class DevelopmentConfig(Config):
218 DEBUG = True
219
da00160 Fixed some small typos in the documentation.
Sam Anderson authored
220 class TestingConfig(Config):
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
221 TESTING = True
222
223 To enable such a config you just have to call into
224 :meth:`~flask.Config.from_object`::
225
226 app.config.from_object('configmodule.ProductionConfig')
227
228 There are many different ways and it's up to you how you want to manage
34fcd19 @mitsuhiko Added chapter about fabric based deployments
authored
229 your configuration files. However here a list of good recommendations:
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
230
231 - keep a default configuration in version control. Either populate the
232 config with this default configuration or import it in your own
233 configuration files before overriding values.
234 - use an environment variable to switch between the configurations.
235 This can be done from outside the Python interpreter and makes
236 development and deployment much easier because you can quickly and
237 easily switch between different configs without having to touch the
238 code at all. If you are working often on different projects you can
239 even create your own script for sourcing that activates a virtualenv
240 and exports the development configuration for you.
241 - Use a tool like `fabric`_ in production to push code and
6875a05 @rduplain Fixed small typos in docs. Added a cross-ref.
rduplain authored
242 configurations separately to the production server(s). For some
34fcd19 @mitsuhiko Added chapter about fabric based deployments
authored
243 details about how to do that, head over to the :ref:`deploy` pattern.
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
244
245 .. _fabric: http://fabfile.org/
Something went wrong with that request. Please try again.