Skip to content

HTTPS clone URL

Subversion checkout URL

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