到目前为止,我发现当 Mako 模板编码不正确时,不可能生成可用的回溯。

除了迭代每一行代码之外,还有什么方法可以调试模板吗?

有帮助吗?

解决方案

马可实际上提供了一个很不错的方式在模板中跟踪误差

from mako import exceptions

try:
    template = lookup.get_template(uri)
    print template.render()
except:
    print exceptions.html_error_template().render()

其他提示

综观烧瓶真子源,我发现称为MAKO_TRANSLATE_EXCEPTIONS一个未记录的配置参数。

此设置在瓶应用程序配置到False,你会得到很好的异常从模板向上冒泡。这实现了作为@Mariano建议同样的事情,而不需要修改源。显然,马里亚诺的回答后加入这个参数。

我把它们分解成碎片,然后重新组装件,当我发现这个问题。

不是很好,但它真的很难说在一个大的,复杂的模板出错了。

使用flask_mako,我觉得它更容易跳过TemplateError代,只是传上来的例外。即在flask_mako.py,注释掉,使TemplateError的一部分,只是做加薪:

def _render(template, context, app):
 """Renders the template and fires the signal"""
app.update_template_context(context)
try:
    rv = template.render(**context)
    template_rendered.send(app, template=template, context=context)
    return rv
except:
    #translated = TemplateError(template)                                                                                                                 
    #raise translated                                                                                                                                     
    raise

}

然后你会看到与模板行号沿导致的问题经常Python异常。

将两个最佳答案与我自己的特殊酱汁结合起来:

from flask.ext.mako import render_template as render_template_1
from mako import exceptions

app.config['MAKO_TRANSLATE_EXCEPTIONS'] = False    # seems to be necessary

def render_template(*args, **kwargs):
    kwargs2 = dict(**kwargs)
    kwargs2['config'] = app.config     # this is irrelevant, but useful
    try:
        return render_template_1(*args, **kwargs2)
    except:
        if app.config.get('DEBUG'):
            return exceptions.html_error_template().render()
        raise

它包装了库存“render_template”函数:

  • 捕获异常,并且
    • 如果调试,则渲染回溯
    • 如果不进行调试,请再次引发异常,以便将其记录下来
  • 使配置可从页面访问(无关)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top