Skip to content
Myr

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

3 files+124 added−10 removed

modified:docs/api.rst+5 added
276 unmodified lines
277278.. autofunction:: render_template_string279280.. autofunction:: get_template_attribute281282Configuration283-------------284285.. autoclass:: Config
modified:tests/flask_tests.py+24 added
25 unmodified lines
26sys.path.append(os.path.join(example_path, 'flaskr'))27sys.path.append(os.path.join(example_path, 'minitwit'))282930# config keys used for the ConfigTestCase31TEST_KEY = 'foo'32SECRET_KEY = 'devkey'333435@contextmanager36def catch_stderr():37 old_stderr = sys.stderr38 sys.stderr = rv = StringIO()
634 unmodified lines
673 assert rv.status_code == 500674 assert rv.data == 'Hello Server Error'675676677class ConfigTestCase(unittest.TestCase):678679 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.config683684 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)688689 def test_config_from_module(self):690 app = flask.Flask(__name__)691 app.config.from_module(__name__)692 self.common_module_test(app)693694695def suite():696 from minitwit_tests import MiniTwitTestCase697 from flaskr_tests import FlaskrTestCase698 suite = unittest.TestSuite()
2 unmodified lines
701 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 lines
modified:flask.py+95 added-10 removed
17 unmodified lines
18from itertools import chain19from jinja2 import Environment, PackageLoader, FileSystemLoader20from 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_string24from werkzeug.routing import Map, Rule25from werkzeug.exceptions import HTTPException, InternalServerError26from werkzeug.contrib.securecookie import SecureCookie27
593 unmodified lines
621 def __set__(self, obj, value):622 obj.config[self.__name__] = value623624625class 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.629630 Either you can fill the config from a config file::631632 app.config.from_pyfile('yourconfig.cfg')633634 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::639640 DEBUG = True641 SECRET_KEY = 'development key'642 app.config.from_module(__name__)643644 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.650651 :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 """656657 def __init__(self, root_path, defaults=None):658 dict.__init__(self, defaults or {})659 self.root_path = root_path660661 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.665666 :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)675676 def from_module(self, module):677 """Updates the values from the given module. A module can be of one678 of the following two types:679680 - a string: in this case the module with that name will be imported681 - an actual module reference: that module is used directly682683 Just the uppercase variables in that module are stored in the config684 after lowercasing. Example usage::685686 app.config.from_module('yourapplication.default_config')687 from yourapplication import default_config688 app.config.from_module(default_config)689690 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.694695 :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()] = value704705 def __repr__(self):706 return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))707708709class 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 for
37 unmodified lines
750 #: when you want to use the secure cookie for instance.751 secret_key = ConfigAttribute('secret_key')752753 #: 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')755756 #: 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')760761 #: 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 lines
786 #: 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 })794710 def __init__(self, import_name, config=None):795 def __init__(self, import_name):796 _PackageBoundObject.__init__(self, import_name)797713 #: 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)802803 #: 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