Add support back for custom resolves on old resolve method
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 9574abe · Browse files · 3 files·+76 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+76 added−10 removed
- tests:+15 added−0 removed
- other:+61 added−10 removed
Provenance
- Commit
c6ddeb7- Tree
b7a49e4- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9574abe
3 files changed+76 added−10 removed
modified:jinja2/runtime.py+58 added-10 removed
15 unmodified lines16 internalcode, object_type_repr, evalcontextfunction17 from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \18 TemplateNotFound19 from jinja2._compat import imap, text_type, iteritems, \20- implements_iterator, implements_to_string, string_types, PY220+ implements_iterator, implements_to_string, string_types, PY2, \21+ with_metaclass22 23 24 # these variables are exported to the template runtime25 __all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',64 unmodified lines90 self.__context.name91 )92 93 94+def _get_func(x):95+ return getattr(x, '__func__', x)96+97+93-class Context(object):98+class ContextMeta(type):99+100+ def __new__(cls, name, bases, d):101+ rv = type.__new__(cls, name, bases, d)102+ if bases == ():103+ return rv104+105+ resolve = _get_func(rv.resolve)106+ default_resolve = _get_func(Context.resolve)107+ resolve_or_missing = _get_func(rv.resolve_or_missing)108+ default_resolve_or_missing = _get_func(Context.resolve_or_missing)109+110+ # If we have a changed resolve but no changed default or missing111+ # resolve we invert the call logic.112+ if resolve is not default_resolve and \113+ resolve_or_missing is default_resolve_or_missing:114+ rv._legacy_resolve_mode = True115+ elif resolve is default_resolve and \116+ resolve_or_missing is default_resolve_or_missing:117+ rv._fast_resolve_mode = True118+119+ return rv120+121+122+def resolve_or_missing(context, key, missing=missing):123+ if key in context.vars:124+ return context.vars[key]125+ if key in context.parent:126+ return context.parent[key]127+ return missing128+129+130+class Context(with_metaclass(ContextMeta)):131 """The template context holds the variables of a template. It stores the132 values passed to the template and also the names the template exports.133 Creating instances is neither supported nor useful as it's created134 automatically at various stages of the template evaluation and should not10 unmodified lines145 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`146 method that doesn't fail with a `KeyError` but returns an147 :class:`Undefined` object for missing variables.148 """112- __slots__ = ('parent', 'vars', 'environment', 'eval_ctx', 'exported_vars',113- 'name', 'blocks', '__weakref__')149+ # XXX: we want to eventually make this be a deprecation warning and150+ # remove it.151+ _legacy_resolve_mode = False152+ _fast_resolve_mode = False153 154 def __init__(self, environment, parent, name, blocks):155 self.parent = parent156 self.vars = {}6 unmodified lines163 # takes place the runtime will update this mapping with the new blocks164 # from the template.165 self.blocks = dict((k, [v]) for k, v in iteritems(blocks))166 167+ # In case we detect the fast resolve mode we can set up an alias168+ # here that bypasses the legacy code logic.169+ if self._fast_resolve_mode:170+ self.resolve_or_missing = resolve_or_missing171+172 def super(self, name, current):173 """Render a parent block."""174 try:175 blocks = self.blocks[name]17 unmodified lines193 def resolve(self, key):194 """Looks up a variable like `__getitem__` or `get` but returns an195 :class:`Undefined` object with the name of the name looked up.196 """197+ if self._legacy_resolve_mode:198+ rv = resolve_or_missing(self, key)199+ else:153- rv = self.resolve_or_missing(key)200+ rv = self.resolve_or_missing(key)201 if rv is missing:202 return self.environment.undefined(name=key)203 return rv204 205 def resolve_or_missing(self, key):206 """Resolves a variable like :meth:`resolve` but returns the207 special `missing` value if it cannot be found.208 """162- if key in self.vars:163- return self.vars[key]164- if key in self.parent:165- return self.parent[key]166- return missing209+ if self._legacy_resolve_mode:210+ rv = self.resolve(key)211+ if isinstance(rv, Undefined):212+ rv = missing213+ return rv214+ return resolve_or_missing(self, key)215 216 def get_exported(self):217 """Get a new dict with the exported variables."""218 return dict((k, self.vars[k]) for k in self.exported_vars)563 unmodified linesmodified:tests/test_regression.py+15 added
503 unmodified lines504 assert t.grouper == 'foo'505 assert t.list == [1, 2]506 assert repr(t) == "('foo', [1, 2])"507 assert str(t) == "('foo', [1, 2])"508+509+ def test_legacy_custom_context(self, env):510+ from jinja2.runtime import Context, Undefined, missing511+512+ class MyContext(Context):513+ def resolve(self, name):514+ if name == 'foo':515+ return 42516+ return super(MyContext, self).resolve(name)517+518+ x = MyContext(env, parent={'bar': 23}, name='foo', blocks={})519+ assert x._legacy_resolve_mode520+ assert x.resolve_or_missing('foo') == 42521+ assert x.resolve_or_missing('bar') == 23522+ assert x.resolve_or_missing('baz') is missingmodified:CHANGES+3 added
5 unmodified lines6 (bugfix release, no release date yet)7 8 - Restored the original repr of the internal `_GroupTuple` because this9 caused issues with ansible and it was an unintended change. (#654)10+- Added back support for custom contexts that override the old `resolve`11+ method since it was hard for people to spot that this could cause a12+ regression.13 14 Version 2.9.415 -------------16 (bugfix release, released on January 10th 2017)480 unmodified lines