Skip to content

Commit 0674ee8

Browse files
committed
Merge branch 'config-namespaces' of https://github.com/mattupstate/flask into config-namespaces
Conflicts: flask/config.py
2 parents 2c2c240 + 90a50f8 commit 0674ee8

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

flask/config.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,5 +193,39 @@ def from_json(self, filename, silent=False):
193193
self[key] = obj[key]
194194
return True
195195

196+
def get_namespace(self, namespace, lowercase=True):
197+
"""Returns a dictionary containing a subset of configuration options
198+
that match the specified namespace/prefix. Example usage::
199+
200+
app.config['IMAGE_STORE_TYPE'] = 'fs'
201+
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
202+
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
203+
image_store_config = app.config.get_namespace('IMAGE_STORE_')
204+
205+
The resulting dictionary `image_store` would look like::
206+
207+
{
208+
'type': 'fs',
209+
'path': '/var/app/images',
210+
'base_url': 'http://img.website.com'
211+
}
212+
213+
This is often useful when configuration options map directly to
214+
keyword arguments in functions or class constructors.
215+
216+
:param namespace: a configuration namespace
217+
:param lowercase: a flag indicating if the keys of the resulting
218+
dictionary should be lowercase
219+
"""
220+
rv = {}
221+
for k, v in self.iteritems():
222+
if not k.startswith(namespace):
223+
continue
224+
key = k[len(namespace):]
225+
if lowercase:
226+
key = key.lower()
227+
rv[key] = v
228+
return rv
229+
196230
def __repr__(self):
197231
return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))

flask/testsuite/config.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,21 @@ def test_session_lifetime(self):
134134
app.config['PERMANENT_SESSION_LIFETIME'] = 42
135135
self.assert_equal(app.permanent_session_lifetime.seconds, 42)
136136

137+
def test_get_namespace(self):
138+
app = flask.Flask(__name__)
139+
app.config['FOO_OPTION_1'] = 'foo option 1'
140+
app.config['FOO_OPTION_2'] = 'foo option 2'
141+
app.config['BAR_STUFF_1'] = 'bar stuff 1'
142+
app.config['BAR_STUFF_2'] = 'bar stuff 2'
143+
foo_options = app.config.get_namespace('FOO_')
144+
self.assert_equal(2, len(foo_options))
145+
self.assert_equal('foo option 1', foo_options['option_1'])
146+
self.assert_equal('foo option 2', foo_options['option_2'])
147+
bar_options = app.config.get_namespace('BAR_', lowercase=False)
148+
self.assert_equal(2, len(bar_options))
149+
self.assert_equal('bar stuff 1', bar_options['STUFF_1'])
150+
self.assert_equal('bar stuff 2', bar_options['STUFF_2'])
151+
137152

138153
class LimitedLoaderMockWrapper(object):
139154
def __init__(self, loader):

0 commit comments

Comments
 (0)