Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 237 lines (179 sloc) 9.369 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
182ee31 @mitsuhiko Added chapter about config
authored
54 =============================== =========================================
55 ``DEBUG`` enable/disable debug mode
f5fb457 @mitsuhiko Added TESTING flag. This fixes #58.
authored
56 ``TESTING`` enable/disable testing mode
8569dfe @mitsuhiko Added a PROPAGATE_EXCEPTIONS flag
authored
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.
182ee31 @mitsuhiko Added chapter about config
authored
62 ``SECRET_KEY`` the secret key
63 ``SESSION_COOKIE_NAME`` the name of the session cookie
64 ``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as
65 :class:`datetime.timedelta` object.
66 ``USE_X_SENDFILE`` enable/disable x-sendfile
f195d92 @mitsuhiko Added proper subdomain support
authored
67 ``LOGGER_NAME`` the name of the logger
68 ``SERVER_NAME`` the name of the server. Required for
6875a05 @rduplain Fixed small typos in docs. Added a cross-ref.
rduplain authored
69 subdomain support (e.g.: ``'localhost'``)
b1790cc @mitsuhiko Added MAX_CONTENT_LENGTH config key
authored
70 ``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will
71 reject incoming requests with a
72 content length greater than this by
73 returning a 413 status code.
182ee31 @mitsuhiko Added chapter about config
authored
74 =============================== =========================================
75
f8f8463 @mitsuhiko Documented cookie problem for #80
authored
76 .. admonition:: More on ``SERVER_NAME``
77
78 The ``SERVER_NAME`` key is used for the subdomain support. Because
79 Flask cannot guess the subdomain part without the knowledge of the
80 actual server name, this is required if you want to work with
81 subdomains. This is also used for the session cookie.
82
83 Please keep in mind that not only Flask has the problem of not knowing
84 what subdomains are, your web browser does as well. Most modern web
85 browsers will not allow cross-subdomain cookies to be set on a
86 server name without dots in it. So if your server name is
87 ``'localhost'`` you will not be able to set a cookie for
88 ``'localhost'`` and every subdomain of it. Please chose a different
89 server name in that case, like ``'myapplication.local'`` and add
90 this name + the subdomains you want to use into your host config
91 or setup a local `bind`_.
92
93 .. _bind: https://www.isc.org/software/bind
94
f195d92 @mitsuhiko Added proper subdomain support
authored
95 .. versionadded:: 0.4
96 ``LOGGER_NAME``
97
98 .. versionadded:: 0.5
99 ``SERVER_NAME``
100
dbb3620 @mitsuhiko Fixed an rst error
authored
101 .. versionadded:: 0.6
102 ``MAX_CONTENT_LENGTH``
b1790cc @mitsuhiko Added MAX_CONTENT_LENGTH config key
authored
103
8569dfe @mitsuhiko Added a PROPAGATE_EXCEPTIONS flag
authored
104 .. versionadded:: 0.7
105 ``PROPAGATE_EXCEPTIONS``
106
182ee31 @mitsuhiko Added chapter about config
authored
107 Configuring from Files
108 ----------------------
109
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
110 Configuration becomes more useful if you can configure from a file, and
111 ideally that file would be outside of the actual application package so that
182ee31 @mitsuhiko Added chapter about config
authored
112 you can install the package with distribute (:ref:`distribute-deployment`)
113 and still modify that file afterwards.
114
115 So a common pattern is this::
116
117 app = Flask(__name__)
118 app.config.from_object('yourapplication.default_settings')
119 app.config.from_envvar('YOURAPPLICATION_SETTINGS')
120
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
121 This first loads the configuration from the
182ee31 @mitsuhiko Added chapter about config
authored
122 `yourapplication.default_settings` module and then overrides the values
123 with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`
124 environment variable points to. This environment variable can be set on
125 Linux or OS X with the export command in the shell before starting the
126 server::
127
128 $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
129 $ python run-app.py
130 * Running on http://127.0.0.1:5000/
131 * Restarting with reloader...
132
133 On Windows systems use the `set` builtin instead::
134
135 >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
136
137 The configuration files themselves are actual Python files. Only values
138 in uppercase are actually stored in the config object later on. So make
139 sure to use uppercase letters for your config keys.
140
2475411 @adamzap Minor config documentation fixes (grammar, etc)
adamzap authored
141 Here is an example configuration file::
182ee31 @mitsuhiko Added chapter about config
authored
142
143 DEBUG = False
144 SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'
145
146 Make sure to load the configuration very early on so that extensions have
147 the ability to access the configuration when starting up. There are other
148 methods on the config object as well to load from individual files. For a
149 complete reference, read the :class:`~flask.Config` object's
150 documentation.
151
152
153 Configuration Best Practices
154 ----------------------------
155
156 The downside with the approach mentioned earlier is that it makes testing
157 a little harder. There is no one 100% solution for this problem in
158 general, but there are a couple of things you can do to improve that
159 experience:
160
161 1. create your application in a function and register modules on it.
162 That way you can create multiple instances of your application with
163 different configurations attached which makes unittesting a lot
164 easier. You can use this to pass in configuration as needed.
165
166 2. Do not write code that needs the configuration at import time. If you
167 limit yourself to request-only accesses to the configuration you can
168 reconfigure the object later on as needed.
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
169
170
171 Development / Production
172 ------------------------
173
174 Most applications need more than one configuration. There will at least
175 be a separate configuration for a production server and one used during
176 development. The easiest way to handle this is to use a default
177 configuration that is always loaded and part of version control, and a
178 separate configuration that overrides the values as necessary as mentioned
179 in the example above::
180
181 app = Flask(__name__)
182 app.config.from_object('yourapplication.default_settings')
183 app.config.from_envvar('YOURAPPLICATION_SETTINGS')
184
185 Then you just have to add a separate `config.py` file and export
186 ``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However
187 there are alternative ways as well. For example you could use imports or
188 subclassing.
189
190 What is very popular in the Django world is to make the import explicit in
191 the config file by adding an ``from yourapplication.default_settings
192 import *`` to the top of the file and then overriding the changes by hand.
193 You could also inspect an environment variable like
194 ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc
195 and import different hardcoded files based on that.
196
197 An interesting pattern is also to use classes and inheritance for
198 configuration::
199
200 class Config(object):
201 DEBUG = False
202 TESTING = False
203 DATABASE_URI = 'sqlite://:memory:'
204
205 class ProductionConfig(Config):
206 DATABASE_URI = 'mysql://user@localhost/foo'
207
208 class DevelopmentConfig(Config):
209 DEBUG = True
210
211 class TestinConfig(Config):
212 TESTING = True
213
214 To enable such a config you just have to call into
215 :meth:`~flask.Config.from_object`::
216
217 app.config.from_object('configmodule.ProductionConfig')
218
219 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
220 your configuration files. However here a list of good recommendations:
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
221
222 - keep a default configuration in version control. Either populate the
223 config with this default configuration or import it in your own
224 configuration files before overriding values.
225 - use an environment variable to switch between the configurations.
226 This can be done from outside the Python interpreter and makes
227 development and deployment much easier because you can quickly and
228 easily switch between different configs without having to touch the
229 code at all. If you are working often on different projects you can
230 even create your own script for sourcing that activates a virtualenv
231 and exports the development configuration for you.
232 - Use a tool like `fabric`_ in production to push code and
6875a05 @rduplain Fixed small typos in docs. Added a cross-ref.
rduplain authored
233 configurations separately to the production server(s). For some
34fcd19 @mitsuhiko Added chapter about fabric based deployments
authored
234 details about how to do that, head over to the :ref:`deploy` pattern.
b7c0e56 @mitsuhiko Added a chapter on configuration options
authored
235
236 .. _fabric: http://fabfile.org/
Something went wrong with that request. Please try again.