Skip to content

Commit fa100b0

Browse files
committed
Performance: Cache Jinja2 environments by search paths
The original code created a new Jinja2 environment for every rendered file because the search path might have changed. This patch uses a cache of Jinja2 environments indexed by search path(s), resulting in cached templates and thus faster rendering.
1 parent 862ac64 commit fa100b0

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

netsim/utils/templates.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#
22
# Common routines for create-topology script
33
#
4+
import functools
45
import pathlib
56
import typing
67

@@ -29,6 +30,14 @@ def add_ansible_filters(ENV: Environment) -> None:
2930
* user_template_path -- subdirectory of user directories to search (current, home)
3031
"""
3132

33+
@functools.lru_cache()
34+
def get_jinja2_env_for_path(template_path: tuple) -> Environment:
35+
ENV = Environment(loader=FileSystemLoader(template_path), \
36+
trim_blocks=True,lstrip_blocks=True, \
37+
undefined=make_logging_undefined(base=StrictUndefined))
38+
add_ansible_filters(ENV)
39+
return ENV
40+
3241
def render_template(
3342
data: typing.Dict,
3443
j2_file: typing.Optional[str] = None,
@@ -50,10 +59,7 @@ def render_template(
5059
template_path = extra_path + template_path
5160
if debug_active('template'):
5261
print(f"TEMPLATE PATH for {j2_file or 'text'}: {template_path}")
53-
ENV = Environment(loader=FileSystemLoader(template_path), \
54-
trim_blocks=True,lstrip_blocks=True, \
55-
undefined=make_logging_undefined(base=StrictUndefined))
56-
add_ansible_filters(ENV)
62+
ENV = get_jinja2_env_for_path(tuple(template_path))
5763
if j2_file is not None:
5864
template = ENV.get_template(j2_file)
5965
elif j2_text is not None:

0 commit comments

Comments
 (0)