提问人:slhck 提问时间:11/16/2023 更新时间:11/16/2023 访问量:39
在 Python 中测试 ansible “to_nice_json” 过滤器 - “没有名为'to_nice_json'的过滤器”
Testing ansible "to_nice_json" filter within Python - "No filter named 'to_nice_json'"
问:
我想使用 Python 脚本测试 Ansible Jinja2 模板,基于此处提供的答案:如何在 ansible 中测试 jinja2 模板?
这段代码曾经工作过,但是我不记得在哪个环境中。现在,当我运行它时,我收到一个关于找不到过滤器的错误:
#!/usr/bin/env bash
# python3 -m pip install ansible
python3 <<EOF
import ansible
import jinja2
print(ansible.__version__)
print(jinja2.__version__)
output = jinja2.Template("Hello {{ var | to_nice_json }}!").render(var=f"{{ 'a': 1, 'b': 2 }}")
print(output)
EOF
这将返回:
2.15.6
3.1.2
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
File "/Users/werner/.pyenv/versions/3.11.6/lib/python3.11/site-packages/jinja2/environment.py", line 1208, in __new__
return env.from_string(source, template_class=cls)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/werner/.pyenv/versions/3.11.6/lib/python3.11/site-packages/jinja2/environment.py", line 1105, in from_string
return cls.from_code(self, self.compile(source), gs, None)
^^^^^^^^^^^^^^^^^^^^
File "/Users/werner/.pyenv/versions/3.11.6/lib/python3.11/site-packages/jinja2/environment.py", line 768, in compile
self.handle_exception(source=source_hint)
File "/Users/werner/.pyenv/versions/3.11.6/lib/python3.11/site-packages/jinja2/environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "<unknown>", line 1, in template
jinja2.exceptions.TemplateAssertionError: No filter named 'to_nice_json'.
pip 依赖项是通过 拉入的。jinja2
ansible
我如何让我的 Python 代码找到正确的过滤器,或者让 jinja2 加载过滤器?
答:
1赞
slhck
11/16/2023
#1
解决方案是将筛选器显式加载到环境中:jinja2
import ansible
import jinja2
from ansible.plugins.filter.core import to_nice_json
print(ansible.__version__)
print(jinja2.__version__)
env = jinja2.Environment()
# Add the Ansible specific filter to the Jinja2 environment
env.filters['to_nice_json'] = to_nice_json
template = env.from_string("Hello {{ var | to_nice_json }}!")
output = template.render(var=f"{{ 'a': 1, 'b': 2 }}")
print(output)
这将打印:
Hello "{ 'a': 1, 'b': 2 }"!
我不确定为什么这在没有所有额外负载的情况下工作。
评论