Improved configuration support.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent e84140a · Browse files · 3 files·+124 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+124 added−10 removed
- tests:+24 added−0 removed
- other:+100 added−10 removed
Provenance
- Commit
c4cac0a- Tree
3a391b8- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e84140a
3 files changed+124 added−10 removed
modified:docs/api.rst+5 added
276 unmodified lines277 278 .. autofunction:: render_template_string279 280 .. autofunction:: get_template_attribute281+282+Configuration283+-------------284+285+.. autoclass:: Configmodified:tests/flask_tests.py+24 added
25 unmodified lines26 sys.path.append(os.path.join(example_path, 'flaskr'))27 sys.path.append(os.path.join(example_path, 'minitwit'))28 29 30+# config keys used for the ConfigTestCase31+TEST_KEY = 'foo'32+SECRET_KEY = 'devkey'33+34+35 @contextmanager36 def catch_stderr():37 old_stderr = sys.stderr38 sys.stderr = rv = StringIO()634 unmodified lines673 assert rv.status_code == 500674 assert rv.data == 'Hello Server Error'675 676 677+class ConfigTestCase(unittest.TestCase):678+679+ def common_module_test(self, app):680+ assert app.secret_key == 'devkey'681+ assert app.config['test_key'] == 'foo'682+ assert 'ConfigTestCase' not in app.config683+684+ def test_config_from_file(self):685+ app = flask.Flask(__name__)686+ app.config.from_pyfile('flask_tests.py')687+ self.common_module_test(app)688+689+ def test_config_from_module(self):690+ app = flask.Flask(__name__)691+ app.config.from_module(__name__)692+ self.common_module_test(app)693+694+695 def suite():696 from minitwit_tests import MiniTwitTestCase697 from flaskr_tests import FlaskrTestCase698 suite = unittest.TestSuite()2 unmodified lines701 suite.addTest(unittest.makeSuite(TemplatingTestCase))702 suite.addTest(unittest.makeSuite(ModuleTestCase))703 suite.addTest(unittest.makeSuite(SendfileTestCase))704 suite.addTest(unittest.makeSuite(LoggingTestCase))705+ suite.addTest(unittest.makeSuite(ConfigTestCase))706 if flask.json_available:707 suite.addTest(unittest.makeSuite(JSONTestCase))708 suite.addTest(unittest.makeSuite(MiniTwitTestCase))709 suite.addTest(unittest.makeSuite(FlaskrTestCase))5 unmodified linesmodified:flask.py+95 added-10 removed
17 unmodified lines18 from itertools import chain19 from jinja2 import Environment, PackageLoader, FileSystemLoader20 from werkzeug import Request as RequestBase, Response as ResponseBase, \21 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \22- ImmutableDict, cached_property, wrap_file, Headers22+ ImmutableDict, cached_property, wrap_file, Headers, \23+ import_string24 from werkzeug.routing import Map, Rule25 from werkzeug.exceptions import HTTPException, InternalServerError26 from werkzeug.contrib.securecookie import SecureCookie27 593 unmodified lines621 def __set__(self, obj, value):622 obj.config[self.__name__] = value623 624 625+class Config(dict):626+ """Works exactly like a dict but provides ways to fill it from files627+ or special dictionaries. There are two common patterns to populate the628+ config.629+630+ Either you can fill the config from a config file::631+632+ app.config.from_pyfile('yourconfig.cfg')633+634+ Or alternatively you can define the configuration options in the635+ module that calls :meth:`from_module` or provide an import path to636+ a module that should be loaded. It is also possible to tell it to637+ use the same module and with that provide the configuration values638+ just before the call::639+640+ DEBUG = True641+ SECRET_KEY = 'development key'642+ app.config.from_module(__name__)643+644+ In both cases (loading from any Python file or loading from modules),645+ only uppercase keys are added to the config. The actual keys in the646+ config are however lowercased so they are converted for you. This makes647+ it possible to use lowercase values in the config file for temporary648+ values that are not added to the config or to define the config keys in649+ the same file that implements the application.650+651+ :param root_path: path to which files are read relative from. When the652+ config object is created by the application, this is653+ the application's :attr:`~flask.Flask.root_path`.654+ :param defaults: an optional dictionary of default values655+ """656+657+ def __init__(self, root_path, defaults=None):658+ dict.__init__(self, defaults or {})659+ self.root_path = root_path660+661+ def from_pyfile(self, filename):662+ """Updates the values in the config from a Python file. This function663+ behaves as if the file was imported as module with the664+ :meth:`from_module` function.665+666+ :param filename: the filename of the config. This can either be an667+ absolute filename or a filename relative to the668+ root path.669+ """670+ filename = os.path.join(self.root_path, filename)671+ d = type(sys)('config')672+ d.__file__ = filename673+ execfile(filename, d.__dict__)674+ self.from_module(d)675+676+ def from_module(self, module):677+ """Updates the values from the given module. A module can be of one678+ of the following two types:679+680+ - a string: in this case the module with that name will be imported681+ - an actual module reference: that module is used directly682+683+ Just the uppercase variables in that module are stored in the config684+ after lowercasing. Example usage::685+686+ app.config.from_module('yourapplication.default_config')687+ from yourapplication import default_config688+ app.config.from_module(default_config)689+690+ You should not use this function to load the actual configuration but691+ rather configuration defaults. The actual config should be loaded692+ with :meth;`from_pyfile` and ideally from a location not within the693+ package because the package might be installed system wide.694+695+ :param module: an import name or module696+ """697+ if isinstance(module, basestring):698+ d = import_string(module).__dict__699+ else:700+ d = module.__dict__701+ for key, value in d.iteritems():702+ if key.isupper():703+ self[key.lower()] = value704+705+ def __repr__(self):706+ return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))707+708+709 class Flask(_PackageBoundObject):710 """The flask object implements a WSGI application and acts as the central711 object. It is passed the name of the module or package of the712 application. Once it is created it will act as a central registry for37 unmodified lines750 #: when you want to use the secure cookie for instance.751 secret_key = ConfigAttribute('secret_key')752 753 #: The secure cookie uses this for the name of the session cookie669- session_cookie_name = ConfigAttribute('session.cookie_name')754+ session_cookie_name = ConfigAttribute('session_cookie_name')755 756 #: A :class:`~datetime.timedelta` which is used to set the expiration757 #: date of a permanent session. The default is 31 days which makes a758 #: permanent session survive for roughly one month.674- permanent_session_lifetime = ConfigAttribute('session.permanent_lifetime')759+ permanent_session_lifetime = ConfigAttribute('permanent_session_lifetime')760 761 #: Enable this if you want to use the X-Sendfile feature. Keep in762 #: mind that the server has to support this. This only affects files763 #: sent with the :func:`send_file` method.22 unmodified lines786 #: default configuration parameters787 default_config = ImmutableDict({788 'debug': False,789 'secret_key': None,705- 'session.cookie_name': 'session',706- 'session.permanent_lifetime': timedelta(days=31),790+ 'session_cookie_name': 'session',791+ 'permanent_session_lifetime': timedelta(days=31),792 'use_x_sendfile': False793 })794 710- def __init__(self, import_name, config=None):795+ def __init__(self, import_name):796 _PackageBoundObject.__init__(self, import_name)797 713- #: the configuration dictionary714- self.config = self.default_config.copy()715- if config:716- self.config.update(config)798+ #: the configuration dictionary as :class:`Config`. This behaves799+ #: exactly like a regular dictionary but supports additional methods800+ #: to load a config from files.801+ self.config = Config(self.root_path, self.default_config)802 803 #: a dictionary of all view functions registered. The keys will804 #: be function names which are also used to generate URLs and805 #: the values are the function objects themselves.532 unmodified lines