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 68278fd · 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
282 unmodified lines
283284.. autofunction:: render_template_string285286.. autofunction:: get_template_attribute287288Configuration289-------------290291.. 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()
651 unmodified lines
690 assert rv.status_code == 500691 assert rv.data == 'Hello Server Error'692693694class ConfigTestCase(unittest.TestCase):695696 def common_module_test(self, app):697 assert app.secret_key == 'devkey'698 assert app.config['test_key'] == 'foo'699 assert 'ConfigTestCase' not in app.config700701 def test_config_from_file(self):702 app = flask.Flask(__name__)703 app.config.from_pyfile('flask_tests.py')704 self.common_module_test(app)705706 def test_config_from_module(self):707 app = flask.Flask(__name__)708 app.config.from_module(__name__)709 self.common_module_test(app)710711712def suite():713 from minitwit_tests import MiniTwitTestCase714 from flaskr_tests import FlaskrTestCase715 suite = unittest.TestSuite()
2 unmodified lines
718 suite.addTest(unittest.makeSuite(TemplatingTestCase))719 suite.addTest(unittest.makeSuite(ModuleTestCase))720 suite.addTest(unittest.makeSuite(SendfileTestCase))721 suite.addTest(unittest.makeSuite(LoggingTestCase))722 suite.addTest(unittest.makeSuite(ConfigTestCase))723 if flask.json_available:724 suite.addTest(unittest.makeSuite(JSONTestCase))725 suite.addTest(unittest.makeSuite(MiniTwitTestCase))726 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
602 unmodified lines
630 def __set__(self, obj, value):631 obj.config[self.__name__] = value632633634class Config(dict):635 """Works exactly like a dict but provides ways to fill it from files636 or special dictionaries. There are two common patterns to populate the637 config.638639 Either you can fill the config from a config file::640641 app.config.from_pyfile('yourconfig.cfg')642643 Or alternatively you can define the configuration options in the644 module that calls :meth:`from_module` or provide an import path to645 a module that should be loaded. It is also possible to tell it to646 use the same module and with that provide the configuration values647 just before the call::648649 DEBUG = True650 SECRET_KEY = 'development key'651 app.config.from_module(__name__)652653 In both cases (loading from any Python file or loading from modules),654 only uppercase keys are added to the config. The actual keys in the655 config are however lowercased so they are converted for you. This makes656 it possible to use lowercase values in the config file for temporary657 values that are not added to the config or to define the config keys in658 the same file that implements the application.659660 :param root_path: path to which files are read relative from. When the661 config object is created by the application, this is662 the application's :attr:`~flask.Flask.root_path`.663 :param defaults: an optional dictionary of default values664 """665666 def __init__(self, root_path, defaults=None):667 dict.__init__(self, defaults or {})668 self.root_path = root_path669670 def from_pyfile(self, filename):671 """Updates the values in the config from a Python file. This function672 behaves as if the file was imported as module with the673 :meth:`from_module` function.674675 :param filename: the filename of the config. This can either be an676 absolute filename or a filename relative to the677 root path.678 """679 filename = os.path.join(self.root_path, filename)680 d = type(sys)('config')681 d.__file__ = filename682 execfile(filename, d.__dict__)683 self.from_module(d)684685 def from_module(self, module):686 """Updates the values from the given module. A module can be of one687 of the following two types:688689 - a string: in this case the module with that name will be imported690 - an actual module reference: that module is used directly691692 Just the uppercase variables in that module are stored in the config693 after lowercasing. Example usage::694695 app.config.from_module('yourapplication.default_config')696 from yourapplication import default_config697 app.config.from_module(default_config)698699 You should not use this function to load the actual configuration but700 rather configuration defaults. The actual config should be loaded701 with :meth;`from_pyfile` and ideally from a location not within the702 package because the package might be installed system wide.703704 :param module: an import name or module705 """706 if isinstance(module, basestring):707 d = import_string(module).__dict__708 else:709 d = module.__dict__710 for key, value in d.iteritems():711 if key.isupper():712 self[key.lower()] = value713714 def __repr__(self):715 return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))716717718class Flask(_PackageBoundObject):719 """The flask object implements a WSGI application and acts as the central720 object. It is passed the name of the module or package of the721 application. Once it is created it will act as a central registry for
37 unmodified lines
759 #: when you want to use the secure cookie for instance.760 secret_key = ConfigAttribute('secret_key')761762 #: The secure cookie uses this for the name of the session cookie678 session_cookie_name = ConfigAttribute('session.cookie_name')763 session_cookie_name = ConfigAttribute('session_cookie_name')764765 #: A :class:`~datetime.timedelta` which is used to set the expiration766 #: date of a permanent session. The default is 31 days which makes a767 #: permanent session survive for roughly one month.683 permanent_session_lifetime = ConfigAttribute('session.permanent_lifetime')768 permanent_session_lifetime = ConfigAttribute('permanent_session_lifetime')769770 #: Enable this if you want to use the X-Sendfile feature. Keep in771 #: mind that the server has to support this. This only affects files772 #: sent with the :func:`send_file` method.
22 unmodified lines
795 #: default configuration parameters796 default_config = ImmutableDict({797 'debug': False,798 'secret_key': None,714 'session.cookie_name': 'session',715 'session.permanent_lifetime': timedelta(days=31),799 'session_cookie_name': 'session',800 'permanent_session_lifetime': timedelta(days=31),801 'use_x_sendfile': False802 })803719 def __init__(self, import_name, config=None):804 def __init__(self, import_name):805 _PackageBoundObject.__init__(self, import_name)806722 #: the configuration dictionary723 self.config = self.default_config.copy()724 if config:725 self.config.update(config)807 #: the configuration dictionary as :class:`Config`. This behaves808 #: exactly like a regular dictionary but supports additional methods809 #: to load a config from files.810 self.config = Config(self.root_path, self.default_config)811812 #: a dictionary of all view functions registered. The keys will813 #: be function names which are also used to generate URLs and814 #: the values are the function objects themselves.
565 unmodified lines