如何调试 Mako 模板?

发布于 2024-07-11 08:54:06 字数 80 浏览 5 评论 0原文

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

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

So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly.

Is there any way to debug templates besides iterating for every line of code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

紅太極 2024-07-18 08:54:06

Mako 实际上提供了一种非常好的方法来跟踪模板中的错误

from mako import exceptions

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

Mako actually provides a 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()
伴随着你 2024-07-18 08:54:06

查看 Flask-Mako 源代码,我发现了一个名为 MAKO_TRANSLATE_EXCEPTIONS

在 Flask 应用程序配置中将其设置为 False,您将从模板中得到很好的异常。 这完成了与 @Mariano 建议相同的事情,而不需要编辑源代码。 显然,这个参数是在马里亚诺回答后添加的。

Looking at the Flask-Mako source, I found an undocumented configuration parameter called MAKO_TRANSLATE_EXCEPTIONS.

Set this to False in your Flask app config and you'll get nice exceptions bubbling up from the template. This accomplishes the same thing as @Mariano suggested, without needing to edit the source. Apparently, this parameter was added after Mariano's answer.

我们只是彼此的过ke 2024-07-18 08:54:06

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

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

I break them down into pieces, and then reassemble the pieces when I've found the problem.

Not good, but it's really hard to tell what went wrong in a big, complex template.

沩ん囻菔务 2024-07-18 08:54:06

我对 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

My main frustration with Mako was that it was hard to see what was happening in the template. As the template code is a runnable object that is in-memory, no debugger can look into it.

One solution is to write the template code to file, and re-run the template using this file as a standard python module. Then you can debug to your hearts content.

An example:

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
有深☉意 2024-07-18 08:54:06

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

Using flask_mako, I find it's easier to skip over the TemplateError generation and just pass up the exception. I.e. in flask_mako.py, comment out the part that makes the TemplateError and just do a raise:

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

}

Then you'll see a regular python exception that caused the problem along with line numbers in the template.

辞取 2024-07-18 08:54:06

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

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”函数:

  • 捕获异常,以及
    • 如果进行调试,则渲染回溯
    • 如果不进行调试,请再次引发异常,以便将其记录下来
  • 使配置可以从页面访问(不相关)

Combining the two top answers with my own special sauce:

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

It wraps the stock "render_template" function:

  • catch exceptions, and
    • if debugging, render a backtrace
    • if not debugging, raise the exception again so it will be logged
  • make config accessible from the page (irrelevant)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文