Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 385 lines (301 sloc) 16.646 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
713ced6 @plaes Improve configuration docs a bit
plaes authored
8 Applications need some kind of configuration. There are different settings
9 you might want to change depending on the application environment like
10 toggling the debug mode, setting the secret key, and other such
11 environment-specific things.
182ee31 @mitsuhiko Added chapter about config
authored
12
13 The way Flask is designed usually requires the configuration to be
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
14 available when the application starts up. You can hardcode the
15 configuration in the code, which for many small applications is not
182ee31 @mitsuhiko Added chapter about config
authored
16 actually that bad, but there are better ways.
17
18 Independent of how you load your config, there is a config object
19 available which holds the loaded configuration values:
20 The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`
21 object. This is the place where Flask itself puts certain configuration
22 values and also where extensions can put their configuration values. But
23 this is also where you can have your own configuration.
24
25 Configuration Basics
26 --------------------
27
28 The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and
29 can be modified just like any dictionary::
30
31 app = Flask(__name__)
32 app.config['DEBUG'] = True
33
34 Certain configuration values are also forwarded to the
713ced6 @plaes Improve configuration docs a bit
plaes authored
35 :attr:`~flask.Flask` object so you can read and write them from there::
182ee31 @mitsuhiko Added chapter about config
authored
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
ccf4641 @mitsuhiko Added finer control over the session cookie parameters
authored
73 ``SESSION_COOKIE_DOMAIN`` the domain for the session cookie. If
74 this is not set, the cookie will be
75 valid for all subdomains of
76 ``SERVER_NAME``.
77 ``SESSION_COOKIE_PATH`` the path for the session cookie. If
78 this is not set the cookie will be valid
79 for all of ``APPLICATION_ROOT`` or if
80 that is not set for ``'/'``.
81 ``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set
82 with the httponly flag. Defaults to
83 `True`.
84 ``SESSION_COOKIE_SECURE`` controls if the cookie should be set
85 with the secure flag. Defaults to
86 `False`.
e71a5ff @mitsuhiko Started work on new request dispatching. Unittests not yet updated
authored
87 ``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as
88 :class:`datetime.timedelta` object.
6dccf77 @mitsuhiko PERMANENT_SESSION_LIFETIME can now be an integer. This fixes #310
authored
89 Starting with Flask 0.8 this can also be
90 an integer representing seconds.
e71a5ff @mitsuhiko Started work on new request dispatching. Unittests not yet updated
authored
91 ``USE_X_SENDFILE`` enable/disable x-sendfile
92 ``LOGGER_NAME`` the name of the logger
aaa24fc @mitsuhiko Merge branch 'master' into blueprints
authored
93 ``SERVER_NAME`` the name and port number of the server.
94 Required for subdomain support (e.g.:
6d0b326 @mitsuhiko Mention localhost:5000 being pointless in the docs. It already says …
authored
95 ``'myapp.dev:5000'``) Note that
96 localhost does not support subdomains so
396c4bd @mitsuhiko Fixed a typo. "Does not" of course
authored
97 setting this to “localhost” does not
98 help.
c844d02 @mitsuhiko Added the APPLICATION_ROOT configuration variable which is used by se…
authored
99 ``APPLICATION_ROOT`` If the application does not occupy
100 a whole domain or subdomain this can
101 be set to the path where the application
102 is configured to live. This is for
103 session cookie as path value. If
104 domains are used, this should be
105 ``None``.
e71a5ff @mitsuhiko Started work on new request dispatching. Unittests not yet updated
authored
106 ``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will
107 reject incoming requests with a
108 content length greater than this by
109 returning a 413 status code.
7155f11 @mitsuhiko Added HTTP exception trapping. This should fix #294
authored
110 ``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will
111 not execute the error handlers of HTTP
112 exceptions but instead treat the
113 exception like any other and bubble it
114 through the exception stack. This is
115 helpful for hairy debugging situations
116 where you have to find out where an HTTP
117 exception is coming from.
acac64e @mitsuhiko Don't only catch BadRequest key errors but all bad request errors.
authored
118 ``TRAP_BAD_REQUEST_ERRORS`` Werkzeug's internal data structures that
7155f11 @mitsuhiko Added HTTP exception trapping. This should fix #294
authored
119 deal with request specific data will
120 raise special key errors that are also
acac64e @mitsuhiko Don't only catch BadRequest key errors but all bad request errors.
authored
121 bad request exceptions. Likewise many
122 operations can implicitly fail with a
123 BadRequest exception for consistency.
124 Since it's nice for debugging to know
125 why exactly it failed this flag can be
126 used to debug those situations. If this
7155f11 @mitsuhiko Added HTTP exception trapping. This should fix #294
authored
127 config is set to ``True`` you will get
128 a regular traceback instead.
e71a5ff @mitsuhiko Started work on new request dispatching. Unittests not yet updated
authored
129 ================================= =========================================
182ee31 @mitsuhiko Added chapter about config
authored
130
f8f8463 @mitsuhiko Documented cookie problem for #80
authored
131 .. admonition:: More on ``SERVER_NAME``
132
133 The ``SERVER_NAME`` key is used for the subdomain support. Because
134 Flask cannot guess the subdomain part without the knowledge of the
135 actual server name, this is required if you want to work with
136 subdomains. This is also used for the session cookie.
137
138 Please keep in mind that not only Flask has the problem of not knowing
139 what subdomains are, your web browser does as well. Most modern web
140 browsers will not allow cross-subdomain cookies to be set on a
141 server name without dots in it. So if your server name is
142 ``'localhost'`` you will not be able to set a cookie for
143 ``'localhost'`` and every subdomain of it. Please chose a different
144 server name in that case, like ``'myapplication.local'`` and add
145 this name + the subdomains you want to use into your host config
146 or setup a local `bind`_.
147
148 .. _bind: https://www.isc.org/software/bind
149
f195d92 @mitsuhiko Added proper subdomain support
authored
150 .. versionadded:: 0.4
151 ``LOGGER_NAME``
152
153 .. versionadded:: 0.5
154 ``SERVER_NAME``
155
dbb3620 @mitsuhiko Fixed an rst error
authored
156 .. versionadded:: 0.6
157 ``MAX_CONTENT_LENGTH``
b1790cc @mitsuhiko Added MAX_CONTENT_LENGTH config key
authored
158
8569dfe @mitsuhiko Added a PROPAGATE_EXCEPTIONS flag
authored
159 .. versionadded:: 0.7
e71a5ff @mitsuhiko Started work on new request dispatching. Unittests not yet updated
authored
160 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``
8569dfe @mitsuhiko Added a PROPAGATE_EXCEPTIONS flag
authored
161
7155f11 @mitsuhiko Added HTTP exception trapping. This should fix #294
authored
162 .. versionadded:: 0.8
c844d02 @mitsuhiko Added the APPLICATION_ROOT configuration variable which is used by se…
authored
163 ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,
ccf4641 @mitsuhiko Added finer control over the session cookie parameters
authored
164 ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,
165 ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,
166 ``SESSION_COOKIE_SECURE``
7155f11 @mitsuhiko Added HTTP exception trapping. This should fix #294
authored
167
182ee31 @mitsuhiko Added chapter about config
authored
168 Configuring from Files
169 ----------------------
170
713ced6 @plaes Improve configuration docs a bit
plaes authored
171 Configuration becomes more useful if you can store it in a separate file,
172 ideally located outside the actual application package. This makes
173 packaging and distributing your application possible via various package
174 handling tools (:ref:`distribute-deployment`) and finally modifying the
175 configuration file afterwards.
182ee31 @mitsuhiko Added chapter about config
authored
176
177 So a common pattern is this::
178
179 app = Flask(__name__)
180 app.config.from_object('yourapplication.default_settings')
181 app.config.from_envvar('YOURAPPLICATION_SETTINGS')
182
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
183 This first loads the configuration from the
182ee31 @mitsuhiko Added chapter about config
authored
184 `yourapplication.default_settings` module and then overrides the values
185 with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`
186 environment variable points to. This environment variable can be set on
187 Linux or OS X with the export command in the shell before starting the
188 server::
189
190 $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
191 $ python run-app.py
192 * Running on http://127.0.0.1:5000/
193 * Restarting with reloader...
194
195 On Windows systems use the `set` builtin instead::
196
197 >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
198
199 The configuration files themselves are actual Python files. Only values
200 in uppercase are actually stored in the config object later on. So make
201 sure to use uppercase letters for your config keys.
202
713ced6 @plaes Improve configuration docs a bit
plaes authored
203 Here is an example of a configuration file::
182ee31 @mitsuhiko Added chapter about config
authored
204
713ced6 @plaes Improve configuration docs a bit
plaes authored
205 # Example configuration
182ee31 @mitsuhiko Added chapter about config
authored
206 DEBUG = False
207 SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'
208
713ced6 @plaes Improve configuration docs a bit
plaes authored
209 Make sure to load the configuration very early on, so that extensions have
182ee31 @mitsuhiko Added chapter about config
authored
210 the ability to access the configuration when starting up. There are other
211 methods on the config object as well to load from individual files. For a
212 complete reference, read the :class:`~flask.Config` object's
213 documentation.
214
215
216 Configuration Best Practices
217 ----------------------------
218
219 The downside with the approach mentioned earlier is that it makes testing
713ced6 @plaes Improve configuration docs a bit
plaes authored
220 a little harder. There is no single 100% solution for this problem in
221 general, but there are a couple of things you can keep in mind to improve
222 that experience:
182ee31 @mitsuhiko Added chapter about config
authored
223
d38c61f @mitsuhiko More modules -> blueprints
authored
224 1. create your application in a function and register blueprints on it.
182ee31 @mitsuhiko Added chapter about config
authored
225 That way you can create multiple instances of your application with
226 different configurations attached which makes unittesting a lot
227 easier. You can use this to pass in configuration as needed.
228
229 2. Do not write code that needs the configuration at import time. If you
230 limit yourself to request-only accesses to the configuration you can
231 reconfigure the object later on as needed.
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
232
233
234 Development / Production
235 ------------------------
236
713ced6 @plaes Improve configuration docs a bit
plaes authored
237 Most applications need more than one configuration. There should be at
238 least separate configurations for the production server and the one used
239 during development. The easiest way to handle this is to use a default
240 configuration that is always loaded and part of the version control, and a
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
241 separate configuration that overrides the values as necessary as mentioned
242 in the example above::
243
244 app = Flask(__name__)
245 app.config.from_object('yourapplication.default_settings')
246 app.config.from_envvar('YOURAPPLICATION_SETTINGS')
247
248 Then you just have to add a separate `config.py` file and export
249 ``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However
250 there are alternative ways as well. For example you could use imports or
251 subclassing.
252
253 What is very popular in the Django world is to make the import explicit in
254 the config file by adding an ``from yourapplication.default_settings
255 import *`` to the top of the file and then overriding the changes by hand.
256 You could also inspect an environment variable like
257 ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc
258 and import different hardcoded files based on that.
259
260 An interesting pattern is also to use classes and inheritance for
261 configuration::
262
263 class Config(object):
264 DEBUG = False
265 TESTING = False
266 DATABASE_URI = 'sqlite://:memory:'
267
268 class ProductionConfig(Config):
269 DATABASE_URI = 'mysql://user@localhost/foo'
270
271 class DevelopmentConfig(Config):
272 DEBUG = True
273
da00160 Fixed some small typos in the documentation.
Sam Anderson authored
274 class TestingConfig(Config):
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
275 TESTING = True
276
277 To enable such a config you just have to call into
278 :meth:`~flask.Config.from_object`::
279
280 app.config.from_object('configmodule.ProductionConfig')
281
282 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
283 your configuration files. However here a list of good recommendations:
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
284
285 - keep a default configuration in version control. Either populate the
286 config with this default configuration or import it in your own
287 configuration files before overriding values.
288 - use an environment variable to switch between the configurations.
289 This can be done from outside the Python interpreter and makes
290 development and deployment much easier because you can quickly and
291 easily switch between different configs without having to touch the
292 code at all. If you are working often on different projects you can
293 even create your own script for sourcing that activates a virtualenv
294 and exports the development configuration for you.
295 - Use a tool like `fabric`_ in production to push code and
6875a05 @rduplain Fixed small typos in docs. Added a cross-ref.
rduplain authored
296 configurations separately to the production server(s). For some
086ecdb @mitsuhiko Better reraising of exceptions
authored
297 details about how to do that, head over to the
298 :ref:`fabric-deployment` pattern.
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
299
300 .. _fabric: http://fabfile.org/
187cb80 @mitsuhiko Documented instance root
authored
301
302
303 .. _instance-folders:
304
305 Instance Folders
306 ----------------
307
308 .. versionadded:: 0.8
309
310 Flask 0.8 introduces instance folders. Flask for a long time made it
311 possible to refer to paths relative to the application's folder directly
312 (via :attr:`Flask.root_path`). This was also how many developers loaded
313 configurations stored next to the application. Unfortunately however this
314 only works well if applications are not packages in which case the root
315 path refers to the contents of the package.
316
317 With Flask 0.8 a new attribute was introduced:
318 :attr:`Flask.instance_path`. It refers to a new concept called the
319 “instance folder”. The instance folder is designed to not be under
320 version control and be deployment specific. It's the perfect place to
321 drop things that either change at runtime or configuration files.
322
314f920 @mitsuhiko Updated instance path documentation to explain the $PREFIX lookup
authored
323 You can either explicitly provide the path of the instance folder when
324 creating the Flask application or you can let Flask autodetect the
325 instance folder. For explicit configuration use the `instance_path`
326 parameter::
187cb80 @mitsuhiko Documented instance root
authored
327
9af7554 @mitsuhiko Mention default locations for instance folders
authored
328 app = Flask(__name__, instance_path='/path/to/instance/folder')
329
314f920 @mitsuhiko Updated instance path documentation to explain the $PREFIX lookup
authored
330 Please keep in mind that this path *must* be absolute when provided.
331
332 If the `instance_path` parameter is not provided the following default
333 locations are used:
334
335 - Uninstalled module::
9af7554 @mitsuhiko Mention default locations for instance folders
authored
336
337 /myapp.py
338 /instance
339
314f920 @mitsuhiko Updated instance path documentation to explain the $PREFIX lookup
authored
340 - Uninstalled package::
341
9af7554 @mitsuhiko Mention default locations for instance folders
authored
342 /myapp
343 /__init__.py
344 /instance
187cb80 @mitsuhiko Documented instance root
authored
345
314f920 @mitsuhiko Updated instance path documentation to explain the $PREFIX lookup
authored
346 - Installed module or package::
347
348 $PREFIX/lib/python2.X/site-packages/myapp
349 $PREFIX/var/myapp-instance
350
351 ``$PREFIX`` is the prefix of your Python installation. This can be
352 ``/usr`` or the path to your virtualenv. You can print the value of
353 ``sys.prefix`` to see what the prefix is set to.
187cb80 @mitsuhiko Documented instance root
authored
354
355 Since the config object provided loading of configuration files from
356 relative filenames we made it possible to change the loading via filenames
357 to be relative to the instance path if wanted. The behavior of relative
358 paths in config files can be flipped between “relative to the application
359 root” (the default) to “relative to instance folder” via the
360 `instance_relative_config` switch to the application constructor::
361
362 app = Flask(__name__, instance_relative_config=True)
363
364 Here is a full example of how to configure Flask to preload the config
365 from a module and then override the config from a file in the config
366 folder if it exists::
367
368 app = Flask(__name__, instance_relative_config=True)
369 app.config.from_object('yourapplication.default_settings')
370 app.config.from_pyfile('application.cfg', silent=True)
371
372 The path to the instance folder can be found via the
373 :attr:`Flask.instance_path`. Flask also provides a shortcut to open a
0520425 @mitsuhiko Fixed a typo
authored
374 file from the instance folder with :meth:`Flask.open_instance_resource`.
187cb80 @mitsuhiko Documented instance root
authored
375
376 Example usage for both::
377
e4d9ccd @Cixelyn Changing instance_root to instance_path
Cixelyn authored
378 filename = os.path.join(app.instance_path, 'application.cfg')
187cb80 @mitsuhiko Documented instance root
authored
379 with open(filename) as f:
380 config = f.read()
381
382 # or via open_instance_resource:
383 with app.open_instance_resource('application.cfg') as f:
384 config = f.read()
Something went wrong with that request. Please try again.