Browse Source

Add Config.from_mapping

pull/1136/head
Daniel Neuhäuser 11 years ago
parent
commit
aa40b1731e
  1. 1
      CHANGES
  2. 22
      flask/config.py
  3. 28
      flask/testsuite/config.py

1
CHANGES

@ -36,6 +36,7 @@ Version 1.0
for an extension author to create exceptions that will by default
result in the HTTP error of their choosing, but may be caught with
a custom error handler if desired.
- Added :meth:`flask.Config.from_mapping`.
Version 0.10.2
--------------

22
flask/config.py

@ -193,6 +193,28 @@ class Config(dict):
self[key] = obj[key]
return True
def from_mapping(self, *mapping, **kwargs):
"""Updates the config like :meth:`update` ignoring items with non-upper
keys.
.. versionadded:: 1.0
"""
mappings = []
if len(mapping) == 1:
if hasattr(mapping[0], 'items'):
mappings.append(mapping[0].items())
else:
mappings.append(mapping[0])
elif len(mapping) > 1:
raise TypeError(
'expected at most 1 positional argument, got %d' % len(mapping)
)
mappings.append(kwargs.items())
for mapping in mappings:
for (key, value) in mapping:
if key.isupper():
self[key] = value
def get_namespace(self, namespace, lowercase=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::

28
flask/testsuite/config.py

@ -47,6 +47,34 @@ class ConfigTestCase(FlaskTestCase):
app.config.from_json(os.path.join(current_dir, 'static', 'config.json'))
self.common_object_test(app)
def test_config_from_mapping(self):
app = flask.Flask(__name__)
app.config.from_mapping({
'SECRET_KEY': 'devkey',
'TEST_KEY': 'foo'
})
self.common_object_test(app)
app = flask.Flask(__name__)
app.config.from_mapping([
('SECRET_KEY', 'devkey'),
('TEST_KEY', 'foo')
])
self.common_object_test(app)
app = flask.Flask(__name__)
app.config.from_mapping(
SECRET_KEY='devkey',
TEST_KEY='foo'
)
self.common_object_test(app)
app = flask.Flask(__name__)
with self.assert_raises(TypeError):
app.config.from_mapping(
{}, {}
)
def test_config_from_class(self):
class Base(object):
TEST_KEY = 'foo'

Loading…
Cancel
Save