Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(WIP) refactor: use external jinja2 extensions to factorize code #10

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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