From 114bc08944413b16d71d80046611cb65108c5724 Mon Sep 17 00:00:00 2001 From: Fabien MARTY Date: Fri, 23 Nov 2018 16:57:42 +0100 Subject: [PATCH] refactor: use external jinja2 extensions to factorize code Close: #7 --- envtpl.py | 31 ++++--------------------------- setup.py | 4 ++++ 2 files changed, 8 insertions(+), 27 deletions(-) diff --git a/envtpl.py b/envtpl.py index d1c7863..ac96ca2 100644 --- a/envtpl.py +++ b/envtpl.py @@ -168,10 +168,10 @@ def _render_file(filename, variables, undefined, extra_search_paths=[]): def _render(template_name, loader, variables, undefined): - env = jinja2.Environment(loader=loader, undefined=undefined) - env.filters['from_json'] = from_json - env.filters['shell'] = shell - env.filters['getenv'] = getenv + extension = ["jinja2_getenv_extension", "jinja2_shell_extension", + "jinja2_from_json_extension"] + env = jinja2.Environment(loader=loader, undefined=undefined, + extensions=extensions) env.filters['uuid'] = getuuid template = env.get_template(template_name) @@ -197,29 +197,6 @@ def get_environment(context, prefix=''): yield key[len(prefix):], value -@jinja2.evalcontextfilter -def from_json(eval_ctx, value): - return json.loads(value) - - -@jinja2.evalcontextfilter -def shell(eval_ctx, value, die_on_error=False, encoding="utf8"): - if die_on_error: - cmd = value - else: - cmd = "%s ; exit 0" % value - output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) - return output.decode(encoding) - - -@jinja2.evalcontextfilter -def getenv(eval_ctx, value, default=None): - result = os.environ.get(value, default) - if result is None: - raise Exception("can't find %s environnement variable" % value) - return result - - @jinja2.evalcontextfilter def getuuid(eval_ctx, value, default=None): v = str(uuid.uuid4()).replace('-', '') + value diff --git a/setup.py b/setup.py index 3792e98..fb46547 100644 --- a/setup.py +++ b/setup.py @@ -108,6 +108,10 @@ install_requires = ['Jinja2>=2.7'] if sys.version_info < (2, 7): install_requires.append('argparse>=1.0') +for jext in ("jinja2_getenv_extension", "jinja2_shell_extension", + "jinja2_from_json_extension"): + install_requires.append("-e git+https://github.com/metwork-framework/" + "%s.git#egg=%s" % (jext, jext)) setup( name='envtpl',