Skip to content
Myr

Change environment cache key construction

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Changing from a tuple of the loader ID and template name to a weakref to the loader and the template name should avoid situations whereby the loader has changed, yet the cached templates are returned. This would occur if the id of the new loader matches the old. A weakref is preferred over a direct reference so that the loader can be garbaged collected.

authored by pgjones · committed by pgjones · parent 042dadd · Browse files · 2 files+7 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+7 added−4 removed

  • tests:+5 added−3 removed
  • other:+2 added−1 removed

2 files+7 added−4 removed

modified:jinja2/environment.py+2 added-1 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import os12import sys13import weakref14from functools import reduce, partial15from jinja2 import nodes16from jinja2.defaults import BLOCK_START_STRING, \17 BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \
751 unmodified lines
769 @internalcode770 def _load_template(self, name, globals):771 if self.loader is None:772 raise TypeError('no loader for this environment specified')772 cache_key = (id(self.loader), name)773 cache_key = (weakref.ref(self.loader), name)774 if self.cache is not None:775 template = self.cache.get(cache_key)776 if template is not None and (not self.auto_reload or777 template.is_up_to_date):
429 unmodified lines
modified:tests/test_loader.py+5 added-3 removed
11 unmodified lines
12import sys13import tempfile14import shutil15import pytest16import weakref1718from jinja2 import Environment, loaders19from jinja2._compat import PYPY, PY220from jinja2.loaders import split_template_path
71 unmodified lines
92 t2 = env.get_template('two')93 assert t2 is env.get_template('two')94 assert t1 is env.get_template('one')95 t3 = env.get_template('three')95 assert (id(loader), 'one') in env.cache96 assert (id(loader), 'two') not in env.cache97 assert (id(loader), 'three') in env.cache96 loader_ref = weakref.ref(loader)97 assert (loader_ref, 'one') in env.cache98 assert (loader_ref, 'two') not in env.cache99 assert (loader_ref, 'three') in env.cache100101 def test_cache_loader_change(self):102 loader1 = loaders.DictLoader({'foo': 'one'})103 loader2 = loaders.DictLoader({'foo': 'two'})
131 unmodified lines