deprecated init_jinja_globals
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 4c8c503 · Browse files · 4 files·+88 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+88 added−16 removed
- tests:+20 added−0 removed
- other:+68 added−16 removed
Provenance
- Commit
0da56d7- Tree
6495455- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
4c8c503
4 files changed+88 added−16 removed
modified:flask/app.py+34 added-16 removed
22 unmodified lines23 from werkzeug.exceptions import HTTPException, InternalServerError, \24 MethodNotAllowed25 26 from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \27- _tojson_filter, _endpoint_from_view_func27+ locked_cached_property, _tojson_filter, _endpoint_from_view_func28 from .wrappers import Request, Response29 from .config import ConfigAttribute, Config30 from .ctx import _RequestContext31 from .globals import _request_ctx_stack, request284 unmodified lines316 self.add_url_rule(self.static_path + '/<path:filename>',317 endpoint='static',318 view_func=self.send_static_file)319 320- #: The Jinja2 environment. It is created from the321- #: :attr:`jinja_options`.322- self.jinja_env = self.create_jinja_environment()323- self.init_jinja_globals()324-320 @property321 def propagate_exceptions(self):322 """Returns the value of the `PROPAGATE_EXCEPTIONS` configuration323 value in case it's set, otherwise a sensible default is returned.26 unmodified lines350 from flask.logging import create_logger351 self._logger = rv = create_logger(self)352 return rv353 354+ @locked_cached_property355+ def jinja_env(self):356+ """The Jinja2 environment used to load templates."""357+ rv = self.create_jinja_environment()358+359+ # Hack to support the init_jinja_globals method which is supported360+ # until 1.0 but has an API deficiency.361+ if getattr(self.init_jinja_globals, 'im_func', None) is not \362+ Flask.init_jinja_globals.im_func:363+ from warnings import warn364+ warn(DeprecationWarning('This flask class uses a customized '365+ 'init_jinja_globals() method which is deprecated. '366+ 'Move the code from that method into the '367+ 'create_jinja_environment() method instead.'))368+ self.__dict__['jinja_env'] = rv369+ self.init_jinja_globals()370+371+ return rv372+373 def create_jinja_environment(self):374 """Creates the Jinja2 environment based on :attr:`jinja_options`361- and :meth:`select_jinja_autoescape`.375+ and :meth:`select_jinja_autoescape`. Since 0.7 this also adds376+ the Jinja2 globals and filters after initialization. Override377+ this function to customize the behavior.378 379 .. versionadded:: 0.5380 """381 options = dict(self.jinja_options)382 if 'autoescape' not in options:383 options['autoescape'] = self.select_jinja_autoescape368- return Environment(loader=self.create_jinja_loader(), **options)384+ rv = Environment(loader=self.create_jinja_loader(), **options)385+ rv.globals.update(386+ url_for=url_for,387+ get_flashed_messages=get_flashed_messages388+ )389+ rv.filters['tojson'] = _tojson_filter390+ return rv391 392 def create_jinja_loader(self):393 """Creates the loader for the Jinja2 environment. Can be used to394 override just the loader and keeping the rest unchanged.2 unmodified lines397 """398 return _DispatchingJinjaLoader(self)399 400 def init_jinja_globals(self):379- """Called directly after the environment was created to inject380- some defaults (like `url_for`, `get_flashed_messages` and the381- `tojson` filter.401+ """Deprecated. Used to initialize the Jinja2 globals.402 403 .. versionadded:: 0.5404+ .. versionchanged:: 0.7405+ This method is deprecated with 0.7. Override406+ :meth:`create_jinja_environment` instead.407 """385- self.jinja_env.globals.update(386- url_for=url_for,387- get_flashed_messages=get_flashed_messages388- )389- self.jinja_env.filters['tojson'] = _tojson_filter408 409 def select_jinja_autoescape(self, filename):410 """Returns `True` if autoescaping should be active for the given411 template name.621 unmodified linesmodified:flask/helpers.py+31 added
13 unmodified lines14 import posixpath15 import mimetypes16 from time import time17 from zlib import adler3218+from threading import RLock19 20 # try to load the best simplejson implementation available. If JSON21 # is not installed, we add a failing class.22 json_available = True35 unmodified lines58 else:59 _tojson_filter = json.dumps60 61 62+# sentinel63+_missing = object()64+65+66 # what separators does this operating system provide that are not a slash?67 # this is used by the send_from_directory function to ensure that nobody is68 # able to access files from outside the filesystem.69 _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]369 unmodified lines439 except (KeyError, AttributeError):440 return os.getcwd()441 442 443+class locked_cached_property(object):444+ """A decorator that converts a function into a lazy property. The445+ function wrapped is called the first time to retrieve the result446+ and then that calculated result is used the next time you access447+ the value. Works like the one in Werkzeug but has a lock for448+ thread safety.449+ """450+451+ def __init__(self, func, name=None, doc=None):452+ self.__name__ = name or func.__name__453+ self.__module__ = func.__module__454+ self.__doc__ = doc or func.__doc__455+ self.func = func456+ self.lock = RLock()457+458+ def __get__(self, obj, type=None):459+ if obj is None:460+ return self461+ with self.lock:462+ value = obj.__dict__.get(self.__name__, _missing)463+ if value is _missing:464+ value = self.func(obj)465+ obj.__dict__[self.__name__] = value466+ return value467+468+469 class _PackageBoundObject(object):470 471 def __init__(self, import_name):472 #: The name of the package or module. Do not change this once55 unmodified linesmodified:tests/flask_tests.py+20 added
1562 unmodified lines1563 finally:1564 flask.got_request_exception.disconnect(record, app)1565 1566 1567+class DeprecationsTestCase(unittest.TestCase):1568+1569+ def test_init_jinja_globals(self):1570+ class MyFlask(flask.Flask):1571+ def init_jinja_globals(self):1572+ self.jinja_env.globals['foo'] = '42'1573+1574+ with catch_warnings() as log:1575+ app = MyFlask(__name__)1576+ @app.route('/')1577+ def foo():1578+ return app.jinja_env.globals['foo']1579+1580+ c = app.test_client()1581+ assert c.get('/').data == '42'1582+ assert len(log) == 11583+ assert 'init_jinja_globals' in str(log[0]['message'])1584+1585+1586 def suite():1587 from minitwit_tests import MiniTwitTestCase1588 from flaskr_tests import FlaskrTestCase1589 suite = unittest.TestSuite()4 unmodified lines1594 suite.addTest(unittest.makeSuite(SendfileTestCase))1595 suite.addTest(unittest.makeSuite(LoggingTestCase))1596 suite.addTest(unittest.makeSuite(ConfigTestCase))1597 suite.addTest(unittest.makeSuite(SubdomainTestCase))1598+ suite.addTest(unittest.makeSuite(DeprecationsTestCase))1599 if flask.json_available:1600 suite.addTest(unittest.makeSuite(JSONTestCase))1601 if flask.signals_available:1602 suite.addTest(unittest.makeSuite(TestSignals))7 unmodified linesmodified:CHANGES+3 added
38 unmodified lines39 - Implemented a silent flag for `config.from_pyfile`.40 - Added `teardown_request` decorator, for functions that should run at the end41 of a request regardless of whether an exception occurred.42 - Implemented :func:`flask.has_request_context`43+- Deprecated `init_jinja_globals`. Override the44+ :meth:`~flask.Flask.create_jinja_environment` method instead to45+ achieve the same functionality.46 47 Version 0.6.148 -------------49 159 unmodified lines