Merge branch 'master' of github.com:mitsuhiko/flask
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 · parents 95fa9f2, 69db1e9 · Browse files · 11 files·+146 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+146 added−9 removed
- other:+146 added−9 removed
Provenance
- Commit
36e86be- Tree
7cd27de- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
95fa9f2- Parent 2
69db1e9
11 files changed+146 added−9 removed
modified:docs/conf.py+1 added-1 removed
41 unmodified lines42 master_doc = 'index'43 44 # General information about the project.45 project = u'Flask'46-copyright = u'2013, Armin Ronacher'46+copyright = u'2014, Armin Ronacher'47 48 # The version info for the project you're documenting, acts as replacement for49 # |version| and |release|, also used in various other places throughout the50 # built documents.219 unmodified linesmodified:docs/config.rst+1 added-1 removed
153 unmodified lines154 ``JSON_AS_ASCII`` By default Flask serialize object to155 ascii-encoded JSON. If this is set to156 ``False`` Flask will not encode to ASCII157 and output strings as-is and return158- unicode strings. ``jsonfiy`` will158+ unicode strings. ``jsonify`` will159 automatically encode it in ``utf-8``160 then for transport for instance.161 ``JSON_SORT_KEYS`` By default Flask will serialize JSON162 objects in a way that the keys are279 unmodified linesmodified:docs/errorhandling.rst+1 added-1 removed
267 unmodified lines268 of the box (see :ref:`debug-mode`). If you would like to use another Python269 debugger, note that debuggers interfere with each other. You have to set some270 options in order to use your favorite debugger:271 272-* ``debug`` - whether to enable debug mode and catch exceptinos272+* ``debug`` - whether to enable debug mode and catch exceptions273 * ``use_debugger`` - whether to use the internal Flask debugger274 * ``use_reloader`` - whether to reload and fork the process on exception275 276 ``debug`` must be True (i.e., exceptions must be caught) in order for the other26 unmodified linesmodified:docs/quickstart.rst+2 added
256 unmodified lines257 accessing URLs. By default, a route only answers to `GET` requests, but that258 can be changed by providing the `methods` argument to the259 :meth:`~flask.Flask.route` decorator. Here are some examples::260 261+ from flask import request262+263 @app.route('/login', methods=['GET', 'POST'])264 def login():265 if request.method == 'POST':266 do_the_login()589 unmodified linesadded:flask/testsuite/static/config.json+4 added
1234{ "TEST_KEY": "foo", "SECRET_KEY": "devkey"}modified:flask/testsuite/__init__.py+6 added
155 unmodified lines156 157 def assert_not_in(self, x, y):158 self.assertNotIn(x, y)159 160+ def assert_isinstance(self, obj, cls):161+ self.assertIsInstance(obj, cls)162+163 if sys.version_info[:2] == (2, 6):164 def assertIn(self, x, y):165 assert x in y, "%r unexpectedly not in %r" % (x, y)166 167 def assertNotIn(self, x, y):168 assert x not in y, "%r unexpectedly in %r" % (x, y)169 170+ def assertIsInstance(self, x, y):171+ assert isinstance(x, y), "not isinstance(%r, %r)" % (x, y)172 173+174 class _ExceptionCatcher(object):175 176 def __init__(self, test_case, exc_type):177 self.test_case = test_case75 unmodified linesmodified:flask/testsuite/config.py+44 added
39 unmodified lines40 app = flask.Flask(__name__)41 app.config.from_object(__name__)42 self.common_object_test(app)43 44+ def test_config_from_json(self):45+ app = flask.Flask(__name__)46+ current_dir = os.path.dirname(os.path.abspath(__file__))47+ app.config.from_json(os.path.join(current_dir, 'static', 'config.json'))48+ self.common_object_test(app)49+50 def test_config_from_class(self):51 class Base(object):52 TEST_KEY = 'foo'53 class Test(Base):51 unmodified lines105 else:106 self.assert_true(0, 'expected config')107 self.assert_false(app.config.from_pyfile('missing.cfg', silent=True))108 109+ def test_config_missing_json(self):110+ app = flask.Flask(__name__)111+ try:112+ app.config.from_json('missing.json')113+ except IOError as e:114+ msg = str(e)115+ self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '116+ 'file (No such file or directory):'))117+ self.assert_true(msg.endswith("missing.json'"))118+ else:119+ self.assert_true(0, 'expected config')120+ self.assert_false(app.config.from_json('missing.json', silent=True))121+122+ def test_custom_config_class(self):123+ class Config(flask.Config):124+ pass125+ class Flask(flask.Flask):126+ config_class = Config127+ app = Flask(__name__)128+ self.assert_isinstance(app.config, Config)129+ app.config.from_object(__name__)130+ self.common_object_test(app)131+132 def test_session_lifetime(self):133 app = flask.Flask(__name__)134 app.config['PERMANENT_SESSION_LIFETIME'] = 42135 self.assert_equal(app.permanent_session_lifetime.seconds, 42)136 137+ def test_get_namespace(self):138+ app = flask.Flask(__name__)139+ app.config['FOO_OPTION_1'] = 'foo option 1'140+ app.config['FOO_OPTION_2'] = 'foo option 2'141+ app.config['BAR_STUFF_1'] = 'bar stuff 1'142+ app.config['BAR_STUFF_2'] = 'bar stuff 2'143+ foo_options = app.config.get_namespace('FOO_')144+ self.assert_equal(2, len(foo_options))145+ self.assert_equal('foo option 1', foo_options['option_1'])146+ self.assert_equal('foo option 2', foo_options['option_2'])147+ bar_options = app.config.get_namespace('BAR_', lowercase=False)148+ self.assert_equal(2, len(bar_options))149+ self.assert_equal('bar stuff 1', bar_options['STUFF_1'])150+ self.assert_equal('bar stuff 2', bar_options['STUFF_2'])151 152+153 class LimitedLoaderMockWrapper(object):154 def __init__(self, loader):155 self.loader = loader156 200 unmodified linesmodified:flask/app.py+17 added-4 removed
173 unmodified lines174 request_globals_class = property(_get_request_globals_class,175 _set_request_globals_class)176 del _get_request_globals_class, _set_request_globals_class177 178+ #: The class that is used for the ``config`` attribute of this app.179+ #: Defaults to :class:`~flask.Config`.180+ #:181+ #: Example use cases for a custom class:182+ #:183+ #: 1. Default values for certain config options.184+ #: 2. Access to config values through attributes in addition to keys.185+ #:186+ #: .. versionadded:: 1.0187+ config_class = Config188+189 #: The debug flag. Set this to `True` to enable debugging of the190 #: application. In debug mode the debugger will kick in when an unhandled191 #: exception occurs and the integrated server will automatically reload192 #: the application if changes in the code are detected.427 unmodified lines620 """621 root_path = self.root_path622 if instance_relative:623 root_path = self.instance_path613- return Config(root_path, self.default_config)624+ return self.config_class(root_path, self.default_config)625 626 def auto_find_instance_path(self):627 """Tries to locate the instance path if it was not provided to the628 constructor of the application class. It will basically calculate589 unmodified lines1218 return f1219 1220 @setupmethod1221 def after_request(self, f):1211- """Register a function to be run after each request. Your function1212- must take one parameter, a :attr:`response_class` object and return1213- a new response object or the same (see :meth:`process_response`).1222+ """Register a function to be run after each request.1223 1224+ Your function must take one parameter, an instance of1225+ :attr:`response_class` and return a new response object or the1226+ same (see :meth:`process_response`).1227+1228 As of Flask 0.7 this function might not be executed at the end of the1229 request in case an unhandled exception occurred.1230 """1231 self.after_request_funcs.setdefault(None, []).append(f)628 unmodified linesmodified:flask/blueprints.py+1 added-1 removed
77 unmodified lines78 79 class Blueprint(_PackageBoundObject):80 """Represents a blueprint. A blueprint is an object that records81 functions that will be called with the82- :class:`~flask.blueprint.BlueprintSetupState` later to register functions82+ :class:`~flask.blueprints.BlueprintSetupState` later to register functions83 or other things on the main application. See :ref:`blueprints` for more84 information.85 86 .. versionadded:: 0.7315 unmodified linesmodified:flask/config.py+66 added-1 removed
12 unmodified lines13 import os14 import errno15 16 from werkzeug.utils import import_string17-from ._compat import string_types17+from ._compat import string_types, iteritems18+from . import json19 20 21 class ConfigAttribute(object):22 """Makes an attribute forward to the config"""141 unmodified lines164 for key in dir(obj):165 if key.isupper():166 self[key] = getattr(obj, key)167 168+ def from_json(self, filename, silent=False):169+ """Updates the values in the config from a JSON file. This function170+ behaves as if the JSON object was a dictionary and passed ot the171+ :meth:`from_object` function.172+173+ :param filename: the filename of the JSON file. This can either be an174+ absolute filename or a filename relative to the175+ root path.176+ :param silent: set to `True` if you want silent failure for missing177+ files.178+179+ .. versionadded:: 1.0180+ """181+ filename = os.path.join(self.root_path, filename)182+183+ try:184+ with open(filename) as json_file:185+ obj = json.loads(json_file.read())186+ except IOError as e:187+ if silent and e.errno in (errno.ENOENT, errno.EISDIR):188+ return False189+ e.strerror = 'Unable to load configuration file (%s)' % e.strerror190+ raise191+ for key in obj.keys():192+ if key.isupper():193+ self[key] = obj[key]194+ return True195+196+ def get_namespace(self, namespace, lowercase=True):197+ """Returns a dictionary containing a subset of configuration options198+ that match the specified namespace/prefix. Example usage::199+200+ app.config['IMAGE_STORE_TYPE'] = 'fs'201+ app.config['IMAGE_STORE_PATH'] = '/var/app/images'202+ app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'203+ image_store_config = app.config.get_namespace('IMAGE_STORE_')204+205+ The resulting dictionary `image_store` would look like::206+207+ {208+ 'type': 'fs',209+ 'path': '/var/app/images',210+ 'base_url': 'http://img.website.com'211+ }212+213+ This is often useful when configuration options map directly to214+ keyword arguments in functions or class constructors.215+216+ :param namespace: a configuration namespace217+ :param lowercase: a flag indicating if the keys of the resulting218+ dictionary should be lowercase219+220+ .. versionadded:: 1.0221+ """222+ rv = {}223+ for k, v in iteritems(self):224+ if not k.startswith(namespace):225+ continue226+ key = k[len(namespace):]227+ if lowercase:228+ key = key.lower()229+ rv[key] = v230+ return rv231+232 def __repr__(self):233 return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))modified:CHANGES+3 added
15 unmodified lines16 expire if the browser window closes.17 - Made Flask support custom JSON mimetypes for incoming data.18 - Added support for returning tuples in the form ``(response, headers)``19 from a view function.20+- Added :meth:`flask.Config.from_json`.21+- Added :attr:`flask.Flask.config_class`.22+- Added :meth:`flask.config.Config.get_namespace`.23 24 Version 0.10.225 --------------26 478 unmodified lines