Skip to content
Myr

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

4 files+88 added−16 removed

modified:flask/app.py+34 added-16 removed
22 unmodified lines
23from werkzeug.exceptions import HTTPException, InternalServerError, \24 MethodNotAllowed2526from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \27 _tojson_filter, _endpoint_from_view_func27 locked_cached_property, _tojson_filter, _endpoint_from_view_func28from .wrappers import Request, Response29from .config import ConfigAttribute, Config30from .ctx import _RequestContext31from .globals import _request_ctx_stack, request
284 unmodified lines
316 self.add_url_rule(self.static_path + '/<path:filename>',317 endpoint='static',318 view_func=self.send_static_file)319320 #: The Jinja2 environment. It is created from the321 #: :attr:`jinja_options`.322 self.jinja_env = self.create_jinja_environment()323 self.init_jinja_globals()324320 @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 lines
350 from flask.logging import create_logger351 self._logger = rv = create_logger(self)352 return rv353354 @locked_cached_property355 def jinja_env(self):356 """The Jinja2 environment used to load templates."""357 rv = self.create_jinja_environment()358359 # 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()370371 return rv372373 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.378379 .. 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 rv391392 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 lines
397 """398 return _DispatchingJinjaLoader(self)399400 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.402403 .. 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_filter408409 def select_jinja_autoescape(self, filename):410 """Returns `True` if autoescaping should be active for the given411 template name.
621 unmodified lines
modified:flask/helpers.py+31 added
13 unmodified lines
14import posixpath15import mimetypes16from time import time17from zlib import adler3218from threading import RLock1920# try to load the best simplejson implementation available. If JSON21# is not installed, we add a failing class.22json_available = True
35 unmodified lines
58else:59 _tojson_filter = json.dumps606162# sentinel63_missing = object()646566# 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 lines
439 except (KeyError, AttributeError):440 return os.getcwd()441442443class 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 """450451 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()457458 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 value467468469class _PackageBoundObject(object):470471 def __init__(self, import_name):472 #: The name of the package or module. Do not change this once
55 unmodified lines
modified:tests/flask_tests.py+20 added
1562 unmodified lines
1563 finally:1564 flask.got_request_exception.disconnect(record, app)156515661567class DeprecationsTestCase(unittest.TestCase):15681569 def test_init_jinja_globals(self):1570 class MyFlask(flask.Flask):1571 def init_jinja_globals(self):1572 self.jinja_env.globals['foo'] = '42'15731574 with catch_warnings() as log:1575 app = MyFlask(__name__)1576 @app.route('/')1577 def foo():1578 return app.jinja_env.globals['foo']15791580 c = app.test_client()1581 assert c.get('/').data == '42'1582 assert len(log) == 11583 assert 'init_jinja_globals' in str(log[0]['message'])158415851586def suite():1587 from minitwit_tests import MiniTwitTestCase1588 from flaskr_tests import FlaskrTestCase1589 suite = unittest.TestSuite()
4 unmodified lines
1594 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 lines
modified:CHANGES+3 added
38 unmodified lines
39- 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.4647Version 0.6.148-------------49
159 unmodified lines