From aa40b1731e09e839502994b3b0c22d3f2361d045 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Sun, 27 Jul 2014 11:19:52 +0200 Subject: [PATCH] Add Config.from_mapping --- CHANGES | 1 + flask/config.py | 22 ++++++++++++++++++++++ flask/testsuite/config.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/CHANGES b/CHANGES index 93364231..ec031c53 100644 --- a/CHANGES +++ b/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 -------------- diff --git a/flask/config.py b/flask/config.py index dfc2f6b3..6119f02b 100644 --- a/flask/config.py +++ b/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:: diff --git a/flask/testsuite/config.py b/flask/testsuite/config.py index d0542200..4772fa77 100644 --- a/flask/testsuite/config.py +++ b/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'