gpt4 book ai didi

python - 如何获取 Jinja2 模板中导致异常(TemplateSyntaxError 除外)的行号?

转载 作者:行者123 更新时间:2023-11-28 19:30:13 26 4
gpt4 key购买 nike

当模板包含语法错误时,Jinja 会抛出一个 TemplateSyntaxError,它的 lineno 属性包含发生错误的模板行号。

当发生非语法错误的错误时,如何获取行号?例如,以下标记:

{{ len(SettlementDate)+1 }}

如果 SettlementDate 不是类似列表的东西,则导致 Jinja 抛出 TypeError。我怎样才能找出这个错误发生的地方,以便报告给用户?对于我的用例,提前清理上下文变量不是一种选择。

最佳答案

我刚遇到这个问题。不幸的是,这似乎是一个没有解决方案的常见问题。为了方便下一个角色的研究,这里有一些相关的引用资料:

https://github.com/saltstack/salt/issues/21298 https://github.com/saltstack/salt/issues/28345

是的,这些引用具体与 saltstack 相关,但存在 jinja 中的潜在问题。

我在我的特定用例中构建了一个解决方法:

  try:
output = env.get_template(
"envoy.{}.yaml".format(args.type.lower())
).render(**context)
print("Template is hydrated")
except Exception as e:
print(
"""
Error Generating Template!
--------------------------
Error: {}
Template: {}

An error occurred hydrating the template with the context
parameters. The error exists in either the context or the
template but has nothing to do with the YAML formatting of
the template at this time.

""".format(e,args.template)
)
if args.debug:
print(output)
else:
print("\nTry running with --debug for more info.")
sys.exit(1)

免责声明:在我的实际解决方案中使用 --debug 会产生丑陋的堆栈跟踪,增加用户的学习曲线。您必须阅读该堆栈跟踪以找到特定于模板的行,例如这个:

模板中的文件“/Users/scaldwell/git//src/serviceProxy/.yaml”,第 4 行 {% from "includes/listener.payload.noop.yaml"import payload_listener_noop with context %}

这应该是更干净的输出....也许有一天我会把这个作为周末项目或 Atlassian ShipIt 项目来修复。在那之前,这就是 JINJA 似乎提供的。

关于python - 如何获取 Jinja2 模板中导致异常(TemplateSyntaxError 除外)的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com