Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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