你如何调试Mako模板?

时间:2008-12-23 23:43:30

标签: python debugging templates jinja2 mako

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

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

6 个答案:

答案 0 :(得分:41)

Mako实际上提供了VERY nice way to track down errors in a template

from mako import exceptions

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

答案 1 :(得分:4)

查看Flask-Mako源代码,我发现了一个名为MAKO_TRANSLATE_EXCEPTIONS的未记录的配置参数。

在Flask应用配置中将此设置为False,您将从模板中获得很好的异常。这完成了与@Mariano建议相同的事情,而无需编辑源代码。显然,这个参数是在Mariano回答之后添加的。

答案 2 :(得分:1)

我将它们分解成碎片,然后在我发现问题时重新组装碎片。

不好,但很难说出一个复杂的大模板出了什么问题。

答案 3 :(得分:1)

我对Mako的主要不满是,很难看到模板中正在发生什么。由于模板代码是内存中的可运行对象,因此调试器无法对其进行调查。

一种解决方案是将模板代码写入文件,然后使用此文件作为标准python模块重新运行模板。然后,您可以调试自己的内心内容。

一个例子:

import sys
from mako import exceptions, template 
from mako.template import DefTemplate
from mako.runtime import _render

<Do Great Stuff>

try:
    template.render(**arguments))
except:
    # Try to re-create the error using a proper file template
    # This will give a clearer error message.
    with open('failed_template.py', 'w') as out:
        out.write(template._code)
    import failed_template
    data = dict(callable=failed_template.render_body, **arguments)
    try:
        _render(DefTemplate(template, failed_template.render_body),
                failed_template.render_body,
                [],
                data)
    except:
        msg = '<An error occurred when rendering template for %s>\n'%arguments
        msg += exceptions.text_error_template().render()
        print(msg, file=sys.stderr)
        raise

答案 4 :(得分:0)

使用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异常导致问题以及模板中的行号。

答案 5 :(得分:0)

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

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

它包装了股票&#34; render_template&#34;功能:

  • 捕获异常,并且
    • 如果调试,则渲染回溯
    • 如果没有调试,再次引发异常以便记录
  • 可从页面访问配置(不相关)