From: pgjones Date: Sat, 21 May 2016 15:17:21 +0000 (+0100) Subject: Change environment cache key construction X-Git-Tag: 2.9~27^2~5^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=1a61008d61cff5b6c95f7b7298e47f2b18685247;p=thirdparty%2Fjinja.git Change environment cache key construction 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. --- diff --git a/jinja2/environment.py b/jinja2/environment.py index 67d05dd9..db51e941 100644 --- a/jinja2/environment.py +++ b/jinja2/environment.py @@ -10,6 +10,7 @@ """ import os import sys +import weakref from functools import reduce, partial from jinja2 import nodes from jinja2.defaults import BLOCK_START_STRING, \ @@ -769,7 +770,7 @@ class Environment(object): def _load_template(self, name, globals): if self.loader is None: raise TypeError('no loader for this environment specified') - cache_key = (id(self.loader), name) + cache_key = (weakref.ref(self.loader), name) if self.cache is not None: template = self.cache.get(cache_key) if template is not None and (not self.auto_reload or diff --git a/tests/test_loader.py b/tests/test_loader.py index 6b9d9bb4..b916b911 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -13,6 +13,7 @@ import sys import tempfile import shutil import pytest +import weakref from jinja2 import Environment, loaders from jinja2._compat import PYPY, PY2 @@ -92,9 +93,10 @@ class TestLoaders(): assert t2 is env.get_template('two') assert t1 is env.get_template('one') t3 = env.get_template('three') - assert (id(loader), 'one') in env.cache - assert (id(loader), 'two') not in env.cache - assert (id(loader), 'three') in env.cache + loader_ref = weakref.ref(loader) + assert (loader_ref, 'one') in env.cache + assert (loader_ref, 'two') not in env.cache + assert (loader_ref, 'three') in env.cache def test_cache_loader_change(self): loader1 = loaders.DictLoader({'foo': 'one'})