我有一个xml模板,我使用jinja2模板引擎将数据加载到其中。我试图验证模板中的所有变量是否都提供了:
from jinja2 import Environment, PackageLoader, meta
tmp = JinjaEnvironment().from_string(TEMPLATE)
parsed_content = tmp.environment.parse(TEMPLATE)
for key in meta.find_undeclared_variables(parsed_content):
if key not in data:
print 'Missing ', key
问题是find_undeclared_variables方法不返回嵌套变量。
For example if my data is {'main': {'age': 22, 'height': 6}, 'size': 10}
then that method returns ['main', 'size']
but what I need is ['main.age', 'main'height', 'size']
目标是验证所有变量都被替换。有什么想法吗?
答案 0 :(得分:0)
我找到了有用的软件包:jinja2schema
from jinja2schema import infer, model
def test(self):
for key, val in infer(TEMPLATE).items():
assert key in self.data, 'Missing {}'.format(key)
if type(val) == model.List:
for subkey in val.item.keys():
assert subkey in self.data[key][0], 'Missing {}.{}'.format(key, subkey)
elif type(val) == model.Dictionary:
for subkey in val.keys():
assert subkey in self.data[key], 'Missing {}.{}'.format(key, subkey)