Python - 在Jinja2渲染时记录堆栈跟踪

时间:2013-11-21 09:20:20

标签: python-2.7 stack-trace jinja2

以下代码

import jinja2

class SomeObj(object):
    def call(self):
        x = dict()
        x['raise']

template = jinja2.Template('{{ obj.call() }}')
template.render(obj=SomeObj())

会导致Jinja2崩溃并将以下信息打印到控制台

Traceback (most recent call last):
  File "test.py", line 9, in 
    template.render(obj=SomeObj())
  File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 969, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 742, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "", line 1, in top-level template code
  File "test.py", line 6, in call
    x['raise']
KeyError: 'raise'

它包含自render函数以来的调用跟踪。但是,当我尝试以这种方式跟踪它时

class SomeObj(object):
    def call(self):
        try:
            x = dict()
            x['raise']
        except KeyError:
            import traceback
            traceback.print_exc()

template = jinja2.Template('{{ obj.call() }}')
template.render(obj=SomeObj())

我只有

Traceback (most recent call last):
  File "test.py", line 7, in call
    x['raise']
KeyError: 'raise'

在Jinja2渲染上下文中获取完整堆栈跟踪的正确方法是什么?提前谢谢。

0 个答案:

没有答案