Add get_namespace method on Config object for convenient access of namespaced config options.

This commit is contained in:
Matt Wright 2014-01-23 15:05:37 -05:00
parent de7e2bcf7a
commit 90a50f8b51
2 changed files with 49 additions and 0 deletions

View file

@ -164,5 +164,39 @@ class Config(dict):
if key.isupper():
self[key] = getattr(obj, key)
def get_namespace(self, namespace, lowercase=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::
app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')
The resulting dictionary `image_store` would look like::
{
'type': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}
This is often useful when configuration options map directly to
keyword arguments in functions or class constructors.
:param namespace: a configuration namespace
:param lowercase: a flag indicating if the keys of the resulting
dictionary should be lowercase
"""
rv = {}
for k, v in self.iteritems():
if not k.startswith(namespace):
continue
key = k[len(namespace):]
if lowercase:
key = key.lower()
rv[key] = v
return rv
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))