From 1a61008d61cff5b6c95f7b7298e47f2b18685247 Mon Sep 17 00:00:00 2001 From: pgjones Date: Sat, 21 May 2016 16:17:21 +0100 Subject: [PATCH] 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. --- jinja2/environment.py | 3 ++- tests/test_loader.py | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) 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'}) -- 2.47.2