Skip to content
Myr

Started refactoring of debugging system for better AppEngine/Pylons support.

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

--HG-- branch : trunk extra : rebase_source : 30b87a402e0847f95eaf277d0fc50e1a63177d5b

authored by Armin Ronacher · committed by Armin Ronacher · parent 4435b43 · Browse files · 2 files+126 added−30 removed
This commit

State

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

Diff stats

2 files+126 added−30 removed

  • other:+126 added−30 removed

2 files+126 added−30 removed

modified:jinja2/debug.py+98 added-18 removed
6 unmodified lines
7 ugly stuff with the Python traceback system in order to achieve tracebacks8 with correct line numbers, locals and contents.910 :copyright: (c) 2009 by the Jinja Team.11 :license: BSD.11 :license: BSD, see LICENSE for more details.12"""13import sys14import traceback15from jinja2.utils import CodeType, missing, internal_code16from jinja2.exceptions import TemplateSyntaxError171819class TracebackFrameProxy(object):20 """Proxies a traceback frame."""2122 def __init__(self, tb):23 self.tb = tb2425 def _set_tb_next(self, next):26 if tb_set_next is not None:27 tb_set_next(self.tb, next and next.tb or None)28 self._tb_next = next2930 def _get_tb_next(self):31 return self._tb_next3233 tb_next = property(_get_tb_next, _set_tb_next)34 del _get_tb_next, _set_tb_next3536 @property37 def is_jinja_frame(self):38 return '__jinja_template__' in self.tb.tb_frame.f_globals3940 def __getattr__(self, name):41 return getattr(self.tb, name)424344class ProcessedTraceback(object):45 """Holds a Jinja preprocessed traceback for priting or reraising."""4647 def __init__(self, exc_type, exc_value, frames):48 assert frames, 'no frames for this traceback?'49 self.exc_type = exc_type50 self.exc_value = exc_value51 self.frames = frames5253 def chain_frames(self):54 """Chains the frames. Requires ctypes or the speedups extension."""55 prev_tb = None56 for tb in self.frames:57 if prev_tb is not None:58 prev_tb.tb_next = tb59 prev_tb = tb60 prev_tb.tb_next = None6162 def render_as_text(self, limit=None):63 """Return a string with the traceback."""64 lines = traceback.format_exception(self.exc_type, self.exc_value,65 self.frames[0], limit=limit)66 return ''.join(lines).rstrip()6768 @property69 def is_template_syntax_error(self):70 """`True` if this is a template syntax error."""71 return isinstance(self.exc_value, TemplateSyntaxError)7273 @property74 def exc_info(self):75 """Exception info tuple with a proxy around the frame objects."""76 return self.exc_type, self.exc_value, self.frames[0]7778 @property79 def standard_exc_info(self):80 """Standard python exc_info for re-raising"""81 return self.exc_type, self.exc_value, self.frames[0].tb828384def make_traceback(exc_info, source_hint=None):85 """Creates a processed traceback object from the exc_info."""86 exc_type, exc_value, tb = exc_info87 if isinstance(exc_value, TemplateSyntaxError):88 exc_info = translate_syntax_error(exc_value, source_hint)89 return translate_exception(exc_info)909192def translate_syntax_error(error, source=None):93 """Rewrites a syntax error to please traceback systems."""94 error.source = source95 error.translated = True
7 unmodified lines
103def translate_exception(exc_info):104 """If passed an exc_info it will automatically rewrite the exceptions105 all the way down to the correct line numbers and frames.106 """32 result_tb = prev_tb = None107 initial_tb = tb = exc_info[2].tb_next108 frames = []109110 while tb is not None:111 # skip frames decorated with @internalcode. These are internal112 # calls we can't avoid and that are useless in template debugging113 # 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)114 if tb.tb_frame.f_code in internal_code:115 tb = tb.tb_next116 continue117118 # save a reference to the next frame if we override the current119 # one with a faked one.120 next = tb.tb_next121122 # fake template exceptions123 template = tb.tb_frame.f_globals.get('__jinja_template__')124 if template is not None:125 lineno = template.get_corresponding_lineno(tb.tb_lineno)126 tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,48 lineno, prev_tb)[2]49 if result_tb is None:50 result_tb = tb51 prev_tb = tb52 tb = tb.tb_next127 lineno)[2]12854 return exc_info[:2] + (result_tb or initial_tb,)129 frames.append(TracebackFrameProxy(tb))130 tb = next131132 # if we don't have any exceptions in the frames left, we have to133 # reraise it unchanged.134 # XXX: can we backup here? when could this happen?135 if not frames:136 raise exc_info[0], exc_info[1], exc_info[2]137138 traceback = ProcessedTraceback(exc_info[0], exc_info[1], frames)139 if tb_set_next is not None:140 traceback.chain_frames()141 return traceback14214357def fake_exc_info(exc_info, filename, lineno, tb_back=None):144def fake_exc_info(exc_info, filename, lineno):145 """Helper for `translate_exception`."""146 exc_type, exc_value, tb = exc_info147148 # figure the real context out
52 unmodified lines
201 except:202 exc_info = sys.exc_info()203 new_tb = exc_info[2].tb_next204118 # now we can patch the exc info accordingly119 if tb_set_next is not None:120 if tb_back is not None:121 tb_set_next(tb_back, new_tb)122 if tb is not None:123 tb_set_next(new_tb, tb.tb_next)124205 # return without this frame206 return exc_info[:2] + (new_tb,)207208
70 unmodified lines
modified:jinja2/environment.py+28 added-12 removed
22 unmodified lines
2324# for direct template usage we have up to ten living environments25_spontaneous_environments = LRUCache(10)2627# the function to create jinja traceback objects. This is dynamically28# imported on the first exception in the exception handler.29_make_traceback = None303132def get_spontaneous_environment(*args):33 """Return a new spontaneous environment. A spontaneous environment is an34 unnamed and unaccessible (in theory) environment that is used for35 templates generated from a string and not from the file system.
163 unmodified lines
199 #: shared environments have this set to `True`. A shared environment200 #: must not be modified201 shared = False202203 exception_handler = None204 exception_formatter = None205206 def __init__(self,207 block_start_string=BLOCK_START_STRING,208 block_end_string=BLOCK_END_STRING,209 variable_start_string=VARIABLE_START_STRING,
158 unmodified lines
368 filename = filename.encode('utf-8')369 try:370 return Parser(self, source, name, filename).parse()371 except TemplateSyntaxError, e:365 from jinja2.debug import translate_syntax_error366 exc_type, exc_value, tb = translate_syntax_error(e, source)367 raise exc_type, exc_value, tb372 self.handle_exception(sys.exc_info(), source_hint=source)373374 def lex(self, source, name=None, filename=None):375 """Lex the given sourcecode and return a generator that yields376 tokens as tuples in the form ``(lineno, token_type, value)``.
7 unmodified lines
384 source = unicode(source)385 try:386 return self.lexer.tokeniter(source, name, filename)387 except TemplateSyntaxError, e:383 from jinja2.debug import translate_syntax_error384 exc_type, exc_value, tb = translate_syntax_error(e, source)385 raise exc_type, exc_value, tb388 self.handle_exception(sys.exc_info(), source_hint=source)389390 def preprocess(self, source, name=None, filename=None):391 """Preprocesses the source with all extensions. This is automatically392 called for all parsing and compiling methods but *not* for :meth:`lex`
82 unmodified lines
475 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]476 template = self.from_string(nodes.Template(body, lineno=1))477 return TemplateExpression(template, undefined_to_none)478479 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):480 """Exception handling helper. This is used internally to either raise481 rewritten exceptions or return a rendered traceback for the template.482 """483 global _make_traceback484 if exc_info is None:485 exc_info = sys.exc_info()486 if _make_traceback is None:487 from jinja2.debug import make_traceback as _make_traceback488 traceback = _make_traceback(exc_info, source_hint)489 if rendered and self.exception_formatter is not None:490 return self.exception_formatter(traceback)491 if self.exception_handler is not None:492 self.exception_handler(traceback)493 exc_type, exc_value, tb = traceback.standard_exc_info494 raise exc_type, exc_value, tb495496 def join_path(self, template, parent):497 """Join a template with the parent. By default all the lookups are498 relative to the loader root so this method returns the `template`499 parameter unchanged, but if the paths should be relative to the
144 unmodified lines
644 vars = dict(*args, **kwargs)645 try:646 return concat(self.root_render_func(self.new_context(vars)))647 except:628 from jinja2.debug import translate_exception629 exc_type, exc_value, tb = translate_exception(sys.exc_info())630 raise exc_type, exc_value, tb648 return self.environment.handle_exception(sys.exc_info(), True)649650 def stream(self, *args, **kwargs):651 """Works exactly like :meth:`generate` but returns a652 :class:`TemplateStream`.
12 unmodified lines
665 try:666 for event in self.root_render_func(self.new_context(vars)):667 yield event668 except:651 from jinja2.debug import translate_exception652 exc_type, exc_value, tb = translate_exception(sys.exc_info())653 raise exc_type, exc_value, tb669 yield self.environment.handle_exception(sys.exc_info(), True)670671 def new_context(self, vars=None, shared=False, locals=None):672 """Create a new :class:`Context` for this template. The vars673 provided will be passed to the template. Per default the globals
192 unmodified lines