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

authored by Armin Ronacher · committed by Armin Ronacher · parent d416a97 · 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.
157 unmodified lines
193 #: shared environments have this set to `True`. A shared environment194 #: must not be modified195 shared = False196197 exception_handler = None198 exception_formatter = None199200 def __init__(self,201 block_start_string=BLOCK_START_STRING,202 block_end_string=BLOCK_END_STRING,203 variable_start_string=VARIABLE_START_STRING,
156 unmodified lines
360 filename = filename.encode('utf-8')361 try:362 return Parser(self, source, name, filename).parse()363 except TemplateSyntaxError, e:357 from jinja2.debug import translate_syntax_error358 exc_type, exc_value, tb = translate_syntax_error(e, source)359 raise exc_type, exc_value, tb364 self.handle_exception(sys.exc_info(), source_hint=source)365366 def lex(self, source, name=None, filename=None):367 """Lex the given sourcecode and return a generator that yields368 tokens as tuples in the form ``(lineno, token_type, value)``.
7 unmodified lines
376 source = unicode(source)377 try:378 return self.lexer.tokeniter(source, name, filename)379 except TemplateSyntaxError, e:375 from jinja2.debug import translate_syntax_error376 exc_type, exc_value, tb = translate_syntax_error(e, source)377 raise exc_type, exc_value, tb380 self.handle_exception(sys.exc_info(), source_hint=source)381382 def preprocess(self, source, name=None, filename=None):383 """Preprocesses the source with all extensions. This is automatically384 called for all parsing and compiling methods but *not* for :meth:`lex`
82 unmodified lines
467 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]468 template = self.from_string(nodes.Template(body, lineno=1))469 return TemplateExpression(template, undefined_to_none)470471 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):472 """Exception handling helper. This is used internally to either raise473 rewritten exceptions or return a rendered traceback for the template.474 """475 global _make_traceback476 if exc_info is None:477 exc_info = sys.exc_info()478 if _make_traceback is None:479 from jinja2.debug import make_traceback as _make_traceback480 traceback = _make_traceback(exc_info, source_hint)481 if rendered and self.exception_formatter is not None:482 return self.exception_formatter(traceback)483 if self.exception_handler is not None:484 self.exception_handler(traceback)485 exc_type, exc_value, tb = traceback.standard_exc_info486 raise exc_type, exc_value, tb487488 def join_path(self, template, parent):489 """Join a template with the parent. By default all the lookups are490 relative to the loader root so this method returns the `template`491 parameter unchanged, but if the paths should be relative to the
143 unmodified lines
635 vars = dict(*args, **kwargs)636 try:637 return concat(self.root_render_func(self.new_context(vars)))638 except:619 from jinja2.debug import translate_exception620 exc_type, exc_value, tb = translate_exception(sys.exc_info())621 raise exc_type, exc_value, tb639 return self.environment.handle_exception(sys.exc_info(), True)640641 def stream(self, *args, **kwargs):642 """Works exactly like :meth:`generate` but returns a643 :class:`TemplateStream`.
12 unmodified lines
656 try:657 for event in self.root_render_func(self.new_context(vars)):658 yield event659 except:642 from jinja2.debug import translate_exception643 exc_type, exc_value, tb = translate_exception(sys.exc_info())644 raise exc_type, exc_value, tb660 yield self.environment.handle_exception(sys.exc_info(), True)661662 def new_context(self, vars=None, shared=False, locals=None):663 """Create a new :class:`Context` for this template. The vars664 provided will be passed to the template. Per default the globals
192 unmodified lines