Skip to content
Myr

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 1d02108 · Browse files · 10 files+98 added−28 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+98 added−28 removed

  • tests:+13 added−1 removed
  • other:+85 added−27 removed

10 files+98 added−28 removed

modified:examples/basic/templates/broken.html+2 added-1 removed
added:examples/basic/templates/subbroken.html+3 added
modified:examples/basic/debugger.py+1 added-1 removed
2 unmodified lines
34env = Environment(loader=FileSystemLoader('templates'))56tmpl = env.get_template('broken.html')7print tmpl.render(seq=range(10))7print tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1])
modified:jinja2/debug.py+43 added-18 removed
9 unmodified lines
10 :copyright: (c) 2009 by the Jinja Team.11 :license: BSD.12"""13import sys14from jinja2.utils import CodeType, missing14from jinja2.utils import CodeType, missing, internal_code151617def translate_syntax_error(error, source=None):18 """Rewrites a syntax error to please traceback systems."""19 error.source = source20 error.translated = True21 exc_info = (type(error), error, None)22 filename = error.filename23 if filename is None:24 filename = '<unknown>'25 return fake_exc_info(exc_info, filename, error.lineno)262728def translate_exception(exc_info):29 """If passed an exc_info it will automatically rewrite the exceptions30 all the way down to the correct line numbers and frames.31 """32 result_tb = prev_tb = None33 initial_tb = tb = exc_info[2].tb_next3435 while tb is not None:36 # skip frames decorated with @internalcode. These are internal37 # calls we can't avoid and that are useless in template debugging38 # output.39 if tb_set_next is not None and tb.tb_frame.f_code in internal_code:40 tb_set_next(prev_tb, tb.tb_next)41 tb = tb.tb_next42 continue4344 template = tb.tb_frame.f_globals.get('__jinja_template__')45 if template is not None:46 lineno = template.get_corresponding_lineno(tb.tb_lineno)47 tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
10 unmodified lines
58 """Helper for `translate_exception`."""59 exc_type, exc_value, tb = exc_info6061 # figure the real context out62 if tb is not None:43 real_locals = tb.tb_frame.f_locals.copy()44 ctx = real_locals.get('context')45 if ctx:46 locals = ctx.get_all()63 real_locals = tb.tb_frame.f_locals.copy()64 ctx = real_locals.get('context')65 if ctx:66 locals = ctx.get_all()67 else:68 locals = {}69 for name, value in real_locals.iteritems():70 if name.startswith('l_') and value is not missing:71 locals[name[2:]] = value7273 # if there is a local called __jinja_exception__, we get74 # rid of it to not break the debug functionality.75 locals.pop('__jinja_exception__', None)76 else:77 locals = {}49 for name, value in real_locals.iteritems():50 if name.startswith('l_') and value is not missing:51 locals[name[2:]] = value7853 # if there is a local called __jinja_exception__, we get54 # rid of it to not break the debug functionality.55 locals.pop('__jinja_exception__', None)5679 # assamble fake globals we need80 globals = {81 '__name__': filename,82 '__file__': filename,
6 unmodified lines
8990 # if it's possible, change the name of the code. This won't work91 # on some python environments such as google appengine92 try:71 function = tb.tb_frame.f_code.co_name72 if function == 'root':73 location = 'top-level template code'74 elif function.startswith('block_'):75 location = 'block "%s"' % function[6:]76 else:93 if tb is None:94 location = 'template'95 else:96 function = tb.tb_frame.f_code.co_name97 if function == 'root':98 location = 'top-level template code'99 elif function.startswith('block_'):100 location = 'block "%s"' % function[6:]101 else:102 location = 'template'103 code = CodeType(0, code.co_nlocals, code.co_stacksize,104 code.co_flags, code.co_code, code.co_consts,105 code.co_names, code.co_varnames, filename,106 location, code.co_firstlineno,
92 unmodified lines
modified:jinja2/environment.py+10 added-5 removed
16 unmodified lines
17from jinja2.compiler import generate18from jinja2.runtime import Undefined, new_context19from jinja2.exceptions import TemplateSyntaxError20from jinja2.utils import import_string, LRUCache, Markup, missing, \21 concat, consume21 concat, consume, internalcode222324# for direct template usage we have up to ten living environments25_spontaneous_environments = LRUCache(10)
312 unmodified lines
338 return obj[attribute]339 except (TypeError, LookupError, AttributeError):340 return self.undefined(obj=obj, name=attribute)341342 @internalcode343 def parse(self, source, name=None, filename=None):344 """Parse the sourcecode and return the abstract syntax tree. This345 tree of nodes is used by the compiler to convert the template into346 executable source- or bytecode. This is useful for debugging or to
6 unmodified lines
353 filename = filename.encode('utf-8')354 try:355 return Parser(self, source, name, filename).parse()356 except TemplateSyntaxError, e:356 e.source = source357 raise e357 from jinja2.debug import translate_syntax_error358 exc_type, exc_value, tb = translate_syntax_error(e, source)359 raise exc_type, exc_value, tb360361 def lex(self, source, name=None, filename=None):362 """Lex the given sourcecode and return a generator that yields363 tokens as tuples in the form ``(lineno, token_type, value)``.
7 unmodified lines
371 source = unicode(source)372 try:373 return self.lexer.tokeniter(source, name, filename)374 except TemplateSyntaxError, e:373 e.source = source374 raise e375 from jinja2.debug import translate_syntax_error376 exc_type, exc_value, tb = translate_syntax_error(e, source)377 raise exc_type, exc_value, tb378379 def preprocess(self, source, name=None, filename=None):380 """Preprocesses the source with all extensions. This is automatically381 called for all parsing and compiling methods but *not* for :meth:`lex`
13 unmodified lines
395 if not isinstance(stream, TokenStream):396 stream = TokenStream(stream, name, filename)397 return stream398399 @internalcode400 def compile(self, source, name=None, filename=None, raw=False):401 """Compile a node or template source code. The `name` parameter is402 the load name of the template after it was joined using403 :meth:`join_path` if necessary, not the filename on the file system.
72 unmodified lines
476 joining here.477 """478 return template479480 @internalcode481 def get_template(self, name, parent=None, globals=None):482 """Load a template from the loader. If a loader is configured this483 method ask the loader for the template and returns a :class:`Template`.484 If the `parent` parameter is not `None`, :meth:`join_path` is called
356 unmodified lines
modified:jinja2/exceptions.py+9 added
42 unmodified lines
43 self.name = name44 self.filename = filename45 self.source = None4647 # this is set to True if the debug.translate_syntax_error48 # function translated the syntax error into a new traceback49 self.translated = False5051 def __unicode__(self):52 # for translated errors we only return the message53 if self.translated:54 return self.message.encode('utf-8')5556 # otherwise attach some stuff57 location = 'line %d' % self.lineno58 name = self.filename or self.name59 if name:60 location = 'File "%s", %s' % (name, location)
45 unmodified lines
modified:jinja2/loaders.py+2 added-1 removed
12 unmodified lines
13 from hashlib import sha114except ImportError:15 from sha import new as sha116from jinja2.exceptions import TemplateNotFound17from jinja2.utils import LRUCache, open_if_exists17from jinja2.utils import LRUCache, open_if_exists, internalcode181920def split_template_path(template):21 """Split a path into segments and perform a sanity check. If it detects
56 unmodified lines
78 the template will be reloaded.79 """80 raise TemplateNotFound(template)8182 @internalcode83 def load(self, environment, name, globals=None):84 """Loads a template. This method looks up the template in the cache85 or loads one by calling :meth:`get_source`. Subclasses should not86 override this method as loaders working on collections of other
224 unmodified lines
modified:jinja2/runtime.py+6 added-1 removed
9 unmodified lines
10"""11import sys12from itertools import chain, imap13from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \14 concat, MethodType, FunctionType14 concat, MethodType, FunctionType, internalcode15from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound1718
136 unmodified lines
155 exported variables.156 """157 return dict(self.parent, **self.vars)158159 @internalcode160 def call(__self, __obj, *args, **kwargs):161 """Call the callable with the arguments and keyword arguments162 provided but inject the active context or environment as first163 argument if the callable is a :func:`contextfunction` or
75 unmodified lines
239 self.name, name='super')240 return BlockReference(self.name, self._context, self._stack,241 self._depth + 1)242243 @internalcode244 def __call__(self):245 rv = concat(self._stack[self._depth](self._context))246 if self._context.environment.autoescape:247 rv = Markup(rv)
34 unmodified lines
282283 def __iter__(self):284 return LoopContextIterator(self)285286 @internalcode287 def loop(self, iterable):288 if self._recurse is None:289 raise TypeError('Tried to call non recursive loop. Maybe you '290 "forgot the 'recursive' modifier.")
53 unmodified lines
344 self.catch_kwargs = catch_kwargs345 self.catch_varargs = catch_varargs346 self.caller = caller347348 @internalcode349 def __call__(self, *args, **kwargs):350 arguments = []351 for idx, name in enumerate(self.arguments):352 try:
59 unmodified lines
412 self._undefined_obj = obj413 self._undefined_name = name414 self._undefined_exception = exc415416 @internalcode417 def _fail_with_undefined_error(self, *args, **kwargs):418 """Regular callback function for undefined objects that raises an419 `UndefinedError` on call.420 """
97 unmodified lines
modified:jinja2/utils.py+9 added
33 unmodified lines
3435# special singleton representing missing values for the runtime36missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()3738# internal code39internal_code = set()404142# concatenate a list of strings and convert them to unicode.43# unfortunately there is a bug in python 2.4 and lower that causes44# unicode.join trash the traceback.45_concat = u''.join
76 unmodified lines
122 f.environmentfunction = True123 return f124125126def internalcode(f):127 """Marks the function as internally used"""128 internal_code.add(f.func_code)129 return f130131132def is_undefined(obj):133 """Check if the object passed is undefined. This does nothing more than134 performing an instance check against :class:`Undefined` but looks nicer.135 This can be used for custom filters or tests that want to react to
628 unmodified lines
modified:tests/test_debug.py+13 added-1 removed
29 unmodified lines
30test_syntax_error = '''31>>> tmpl = MODULE.env.get_template('syntaxerror.html')32Traceback (most recent call last):33 ...34TemplateSyntaxError: unknown tag 'endif'34 File "loaderres/templates/syntaxerror.html", line 435 {% endif %}36TemplateSyntaxError: unknown tag 'endif'37'''383940test_regular_syntax_error = '''41>>> from jinja2.exceptions import TemplateSyntaxError42>>> raise TemplateSyntaxError('wtf', 42)43Traceback (most recent call last):44 ...45 File "<doctest test_regular_syntax_error[1]>", line 1, in <module>46 raise TemplateSyntaxError('wtf', 42)47TemplateSyntaxError: wtf48 line 4249'''