Skip to content

Commit

Permalink
refactor: use external jinja2 extensions to factorize code
Browse files Browse the repository at this point in the history
Close: #7
  • Loading branch information
thefab committed Nov 23, 2018
1 parent 3157aa0 commit 114bc08
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 27 deletions.
31 changes: 4 additions & 27 deletions envtpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
4 changes: 4 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down

0 comments on commit 114bc08

Please sign in to comment.