Core: Use strings for Jinja2 template names (#5343)

This commit is contained in:
Noelle Leigh 2022-07-29 13:41:14 -04:00 committed by GitHub
parent c0ce38dba8
commit d28c4bfb93
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 11 deletions

View File

@ -108,8 +108,17 @@ class _TemplateEnvironmentMixin(object):
def contains_template(self, template_id): def contains_template(self, template_id):
return self.environment.loader.contains(template_id) return self.environment.loader.contains(template_id)
@classmethod
def _make_template_id(cls, source):
"""
Return a numeric string that's unique for the lifetime of the source.
Jinja2 expects to template IDs to be strings.
"""
return str(id(source))
def response_template(self, source): def response_template(self, source):
template_id = id(source) template_id = self._make_template_id(source)
if not self.contains_template(template_id): if not self.contains_template(template_id):
collapsed = re.sub( collapsed = re.sub(
self.RIGHT_PATTERN, ">", re.sub(self.LEFT_PATTERN, "<", source) self.RIGHT_PATTERN, ">", re.sub(self.LEFT_PATTERN, "<", source)

View File

@ -184,20 +184,24 @@ def test_response_environment_preserved_by_type():
source_1 = "template" source_1 = "template"
source_2 = "amother template" source_2 = "amother template"
assert not resp_a.contains_template(id(source_1)) assert not resp_a.contains_template(BaseResponse._make_template_id(source_1))
resp_a.response_template(source_1) resp_a.response_template(source_1)
assert resp_a.contains_template(id(source_1)) assert resp_a.contains_template(BaseResponse._make_template_id(source_1))
assert not resp_a.contains_template(id(source_2)) assert not resp_a.contains_template(BaseResponse._make_template_id(source_2))
resp_a.response_template(source_2) resp_a.response_template(source_2)
assert resp_a.contains_template(id(source_2)) assert resp_a.contains_template(BaseResponse._make_template_id(source_2))
assert not resp_b.contains_template(id(source_1)) assert not resp_b.contains_template(BaseResponse._make_template_id(source_1))
assert not resp_b.contains_template(id(source_2)) assert not resp_b.contains_template(BaseResponse._make_template_id(source_2))
assert another_resp_a.contains_template(id(source_1)) assert another_resp_a.contains_template(BaseResponse._make_template_id(source_1))
assert another_resp_a.contains_template(id(source_2)) assert another_resp_a.contains_template(BaseResponse._make_template_id(source_2))
resp_a_new_instance = ResponseA() resp_a_new_instance = ResponseA()
assert resp_a_new_instance.contains_template(id(source_1)) assert resp_a_new_instance.contains_template(
assert resp_a_new_instance.contains_template(id(source_2)) BaseResponse._make_template_id(source_1)
)
assert resp_a_new_instance.contains_template(
BaseResponse._make_template_id(source_2)
)