Skip to content
Myr

Merge pull request #1110 from pallets/patch-traceback

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

rewrite traceback rewriting support

authored by David Lord · committed by GitHub · parents 6c1a62f, cfb789a · Browse files · 6 files+225 added−370 removed
This commit

State

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

Diff stats

6 files+225 added−370 removed

  • tests:+2 added−2 removed
  • other:+223 added−368 removed

6 files+225 added−370 removed

modified:jinja2/asyncsupport.py+2 added-7 removed
9 unmodified lines
10 :license: BSD, see LICENSE for more details.11"""12import asyncio13import inspect14import sys14from functools import update_wrapper1516from jinja2.environment import TemplateModule17from jinja2.runtime import LoopContext
17 unmodified lines
35 try:36 async for event in self.root_render_func(self.new_context(vars)):37 yield event38 except Exception:40 exc_info = sys.exc_info()41 else:42 return43 yield self.environment.handle_exception(exc_info, True)39 yield self.environment.handle_exception()404142def wrap_generate_func(original_generate):43 def _convert_generator(self, loop, args, kwargs):
20 unmodified lines
6465 try:66 return await concat_async(self.root_render_func(ctx))67 except Exception:72 exc_info = sys.exc_info()73 return self.environment.handle_exception(exc_info, True)68 return self.environment.handle_exception()697071def wrap_render_func(original_render):72 def render(self, *args, **kwargs):
192 unmodified lines
modified:jinja2/debug.py+205 added-315 removed
1# -*- coding: utf-8 -*-2"""3 jinja2.debug4 ~~~~~~~~~~~~56 Implements the debug interface for Jinja. This module does some pretty7 ugly stuff with the Python traceback system in order to achieve tracebacks8 with correct line numbers, locals and contents.910 :copyright: (c) 2017 by the Jinja Team.11 :license: BSD, see LICENSE for more details.12"""1import sys14import traceback15from types import TracebackType, CodeType2from types import CodeType16from jinja2.utils import missing, internal_code17from jinja2.exceptions import TemplateSyntaxError18from jinja2._compat import iteritems, reraise, PY2320# on pypy we can take advantage of transparent proxies21try:22 from __pypy__ import tproxy23except ImportError:24 tproxy = None4from jinja2 import TemplateSyntaxError5from jinja2._compat import PYPY6from jinja2.utils import internal_code7from jinja2.utils import missing8927# how does the raise helper look like?28try:29 exec("raise TypeError, 'foo'")30except SyntaxError:31 raise_helper = 'raise __jinja_exception__[1]'32except TypeError:33 raise_helper = 'raise __jinja_exception__[0], __jinja_exception__[1]'10def rewrite_traceback_stack(source=None):11 """Rewrite the current exception to replace any tracebacks from12 within compiled template code with tracebacks that look like they13 came from the template source.1415 This must be called within an ``except`` block.1636class TracebackFrameProxy(object):37 """Proxies a traceback frame."""17 :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18 the current ``exc_info`` is used.19 :param source: For ``TemplateSyntaxError``, the original source if20 known.21 :return: A :meth:`sys.exc_info` tuple that can be re-raised.22 """23 exc_type, exc_value, tb = sys.exc_info()24 # The new stack of traceback objects, to be joined together by25 # tb_set_next later.26 stack = []2739 def __init__(self, tb):40 self.tb = tb41 self._tb_next = None28 if isinstance(exc_value, TemplateSyntaxError):29 exc_value.source = source30 # The exception doesn't need to output location info manually.31 exc_value.translated = True3243 @property44 def tb_next(self):45 return self._tb_next33 try:34 # Remove the old traceback on Python 3, otherwise the frames35 # from the compiler still show up.36 exc_value.with_traceback(None)37 except AttributeError:38 pass3947 def set_next(self, next):48 if tb_set_next is not None:49 try:50 tb_set_next(self.tb, next and next.tb or None)51 except Exception:52 # this function can fail due to all the hackery it does53 # on various python implementations. We just catch errors54 # down and ignore them if necessary.55 pass56 self._tb_next = next40 # Outside of runtime, so the frame isn't executing template41 # code, but it still needs to point at the template.42 tb = fake_traceback(43 exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno44 )45 else:46 # Skip the frame for the render function.47 tb = tb.tb_next4858 @property59 def is_jinja_frame(self):60 return '__jinja_template__' in self.tb.tb_frame.f_globals49 # Build the stack of traceback object, replacing any in template50 # code with the source file and line information.51 while tb is not None:52 # Skip frames decorated with @internalcode. These are internal53 # calls that aren't useful in template debugging output.54 if tb.tb_frame.f_code in internal_code:55 tb = tb.tb_next56 continue5762 def __getattr__(self, name):63 return getattr(self.tb, name)58 template = tb.tb_frame.f_globals.get("__jinja_template__")596566def make_frame_proxy(frame):67 proxy = TracebackFrameProxy(frame)68 if tproxy is None:69 return proxy70 def operation_handler(operation, *args, **kwargs):71 if operation in ('__getattribute__', '__getattr__'):72 return getattr(proxy, args[0])73 elif operation == '__setattr__':74 proxy.__setattr__(*args, **kwargs)60 if template is not None:61 lineno = template.get_corresponding_lineno(tb.tb_lineno)62 fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)63 stack.append(fake_tb)64 else:76 return getattr(proxy, operation)(*args, **kwargs)77 return tproxy(TracebackType, operation_handler)65 stack.append(tb)6667 tb = tb.tb_next6880class ProcessedTraceback(object):81 """Holds a Jinja preprocessed traceback for printing or reraising."""69 tb_next = None7083 def __init__(self, exc_type, exc_value, frames):84 assert frames, 'no frames for this traceback?'85 self.exc_type = exc_type86 self.exc_value = exc_value87 self.frames = frames71 # Assign tb_next in reverse to avoid circular references.72 for tb in reversed(stack):73 tb_next = tb_set_next(tb, tb_next)7489 # newly concatenate the frames (which are proxies)90 prev_tb = None91 for tb in self.frames:92 if prev_tb is not None:93 prev_tb.set_next(tb)94 prev_tb = tb95 prev_tb.set_next(None)75 return exc_type, exc_value, tb_next7697 def render_as_text(self, limit=None):98 """Return a string with the traceback."""99 lines = traceback.format_exception(self.exc_type, self.exc_value,100 self.frames[0], limit=limit)101 return ''.join(lines).rstrip()77103 def render_as_html(self, full=False):104 """Return a unicode string with the traceback as rendered HTML."""105 from jinja2.debugrenderer import render_traceback106 return u'%s\n\n<!--\n%s\n-->' % (107 render_traceback(self, full=full),108 self.render_as_text().decode('utf-8', 'replace')109 )78def fake_traceback(exc_value, tb, filename, lineno):79 """Produce a new traceback object that looks like it came from the80 template source instead of the compiled code. The filename, line81 number, and location name will point to the template, and the local82 variables will be the current template context.83111 @property112 def is_template_syntax_error(self):113 """`True` if this is a template syntax error."""114 return isinstance(self.exc_value, TemplateSyntaxError)115116 @property117 def exc_info(self):118 """Exception info tuple with a proxy around the frame objects."""119 return self.exc_type, self.exc_value, self.frames[0]120121 @property122 def standard_exc_info(self):123 """Standard python exc_info for re-raising"""124 tb = self.frames[0]125 # the frame will be an actual traceback (or transparent proxy) if126 # we are on pypy or a python implementation with support for tproxy127 if type(tb) is not TracebackType:128 tb = tb.tb129 return self.exc_type, self.exc_value, tb130131132def make_traceback(exc_info, source_hint=None):133 """Creates a processed traceback object from the exc_info."""134 exc_type, exc_value, tb = exc_info135 if isinstance(exc_value, TemplateSyntaxError):136 exc_info = translate_syntax_error(exc_value, source_hint)137 initial_skip = 084 :param exc_value: The original exception to be re-raised to create85 the new traceback.86 :param tb: The original traceback to get the local variables and87 code info from.88 :param filename: The template filename.89 :param lineno: The line number in the template source.90 """91 if tb is not None:92 # Replace the real locals with the context that would be93 # available at that point in the template.94 locals = get_template_locals(tb.tb_frame.f_locals)95 locals.pop("__jinja_exception__", None)96 else:139 initial_skip = 1140 return translate_exception(exc_info, initial_skip)97 locals = {}9899 globals = {100 "__name__": filename,101 "__file__": filename,102 "__jinja_exception__": exc_value,103 }104 # Raise an exception at the correct line number.105 code = compile('\n' * (lineno - 1) + "raise __jinja_exception__", filename, "exec")106143def translate_syntax_error(error, source=None):144 """Rewrites a syntax error to please traceback systems."""145 error.source = source146 error.translated = True147 exc_info = (error.__class__, error, None)148 filename = error.filename149 if filename is None:150 filename = '<unknown>'151 return fake_exc_info(exc_info, filename, error.lineno)107 # Build a new code object that points to the template file and108 # replaces the location with a block name.109 try:110 location = "template"111153154def translate_exception(exc_info, initial_skip=0):155 """If passed an exc_info it will automatically rewrite the exceptions156 all the way down to the correct line numbers and frames.157 """158 tb = exc_info[2]159 frames = []160161 # skip some internal frames if wanted162 for x in range(initial_skip):112 if tb is not None:164 tb = tb.tb_next165 initial_tb = tb113 function = tb.tb_frame.f_code.co_name114167 while tb is not None:168 # skip frames decorated with @internalcode. These are internal169 # calls we can't avoid and that are useless in template debugging170 # output.171 if tb.tb_frame.f_code in internal_code:172 tb = tb.tb_next173 continue115 if function == "root":116 location = "top-level template code"117 elif function.startswith("block_"):118 location = 'block "%s"' % function[6:]119175 # save a reference to the next frame if we override the current176 # one with a faked one.177 next = tb.tb_next120 # Collect arguments for the new code object. CodeType only121 # accepts positional arguments, and arguments were inserted in122 # new Python versions.123 code_args = []124179 # fake template exceptions180 template = tb.tb_frame.f_globals.get('__jinja_template__')181 if template is not None:182 lineno = template.get_corresponding_lineno(tb.tb_lineno)183 tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,184 lineno)[2]125 for attr in (126 "argcount",127 "posonlyargcount", # Python 3.8128 "kwonlyargcount", # Python 3129 "nlocals",130 "stacksize",131 "flags",132 "code", # codestring133 "consts", # constants134 "names",135 "varnames",136 ("filename", filename),137 ("name", location),138 "firstlineno",139 "lnotab",140 "freevars",141 "cellvars",142 ):143 if isinstance(attr, tuple):144 # Replace with given value.145 code_args.append(attr[1])146 continue147186 frames.append(make_frame_proxy(tb))187 tb = next148 try:149 # Copy original value if it exists.150 code_args.append(getattr(code, "co_" + attr))151 except AttributeError:152 # Some arguments were added later.153 continue154189 # if we don't have any exceptions in the frames left, we have to190 # reraise it unchanged.191 # XXX: can we backup here? when could this happen?192 if not frames:193 reraise(exc_info[0], exc_info[1], exc_info[2])155 code = CodeType(*code_args)156 except Exception:157 # Some environments such as Google App Engine don't support158 # modifying code objects.159 pass160195 return ProcessedTraceback(exc_info[0], exc_info[1], frames)161 # Execute the new code, which is guaranteed to raise, and return162 # the new traceback without this frame.163 try:164 exec(code, globals, locals)165 except:166 return sys.exc_info()[2].tb_next167168198def get_jinja_locals(real_locals):199 ctx = real_locals.get('context')169def get_template_locals(real_locals):170 """Based on the runtime locals, get the context that would be171 available at that point in the template.172 """173 # Start with the current template context.174 ctx = real_locals.get("context")175176 if ctx:201 locals = ctx.get_all().copy()177 data = ctx.get_all().copy()178 else:203 locals = {}179 data = {}180181 # Might be in a derived context that only sets local variables182 # rather than pushing a context. Local variables follow the scheme183 # l_depth_name. Find the highest-depth local that has a value for184 # each name.185 local_overrides = {}186207 for name, value in iteritems(real_locals):208 if not name.startswith('l_') or value is missing:187 for name, value in real_locals.items():188 if not name.startswith("l_") or value is missing:189 # Not a template variable, or no longer relevant.190 continue191192 try:211 _, depth, name = name.split('_', 2)193 _, depth, name = name.split("_", 2)194 depth = int(depth)195 except ValueError:196 continue197198 cur_depth = local_overrides.get(name, (-1,))[0]199200 if cur_depth < depth:201 local_overrides[name] = (depth, value)202219 for name, (_, value) in iteritems(local_overrides):203 # Modify the context with any derived context.204 for name, (_, value) in local_overrides.items():205 if value is missing:221 locals.pop(name, None)206 data.pop(name, None)207 else:223 locals[name] = value208 data[name] = value209225 return locals210 return data211212228def fake_exc_info(exc_info, filename, lineno):229 """Helper for `translate_exception`."""230 exc_type, exc_value, tb = exc_info231232 # figure the real context out233 if tb is not None:234 locals = get_jinja_locals(tb.tb_frame.f_locals)235236 # if there is a local called __jinja_exception__, we get237 # rid of it to not break the debug functionality.238 locals.pop('__jinja_exception__', None)213if sys.version_info >= (3, 7):214 # tb_next is directly assignable as of Python 3.7215 def tb_set_next(tb, tb_next):216 tb.tb_next = tb_next217 return tb218elif PYPY:219 # PyPy might have special support, and won't work with ctypes.220 try:221 import tputil222 except ImportError:223 # Without tproxy support, use the original traceback.224 def tb_set_next(tb, tb_next):225 return tb226 else:240 locals = {}227 # With tproxy support, create a proxy around the traceback that228 # returns the new tb_next.229 def tb_set_next(tb, tb_next):230 def controller(op):231 if op.opname == "__getattribute__" and op.args[0] == "tb_next":232 return tb_next233242 # assamble fake globals we need243 globals = {244 '__name__': filename,245 '__file__': filename,246 '__jinja_exception__': exc_info[:2],234 return op.delegate()235248 # we don't want to keep the reference to the template around249 # to not cause circular dependencies, but we mark it as Jinja250 # frame for the ProcessedTraceback251 '__jinja_template__': None252 }253254 # and fake the exception255 code = compile('\n' * (lineno - 1) + raise_helper, filename, 'exec')256257 # if it's possible, change the name of the code. This won't work258 # on some python environments such as google appengine259 try:260 if tb is None:261 location = 'template'262 else:263 function = tb.tb_frame.f_code.co_name264 if function == 'root':265 location = 'top-level template code'266 elif function.startswith('block_'):267 location = 'block "%s"' % function[6:]268 else:269 location = 'template'270271 if PY2:272 code = CodeType(0, code.co_nlocals, code.co_stacksize,273 code.co_flags, code.co_code, code.co_consts,274 code.co_names, code.co_varnames, filename,275 location, code.co_firstlineno,276 code.co_lnotab, (), ())277 else:278 code = CodeType(0, code.co_kwonlyargcount,279 code.co_nlocals, code.co_stacksize,280 code.co_flags, code.co_code, code.co_consts,281 code.co_names, code.co_varnames, filename,282 location, code.co_firstlineno,283 code.co_lnotab, (), ())284 except Exception as e:285 pass286287 # execute the code and catch the new traceback288 try:289 exec(code, globals, locals)290 except:291 exc_info = sys.exc_info()292 new_tb = exc_info[2].tb_next293294 # return without this frame295 return exc_info[:2] + (new_tb,)296297298def _init_ugly_crap():299 """This function implements a few ugly things so that we can patch the300 traceback objects. The function returned allows resetting `tb_next` on301 any python traceback object. Do not attempt to use this on non cpython302 interpreters303 """236 return tputil.make_proxy(controller, obj=tb)237else:238 # Use ctypes to assign tb_next at the C level since it's read-only239 # from Python.240 import ctypes305 from types import TracebackType241307 if PY2:308 # figure out size of _Py_ssize_t for Python 2:309 if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):310 _Py_ssize_t = ctypes.c_int64311 else:312 _Py_ssize_t = ctypes.c_int313 else:314 # platform ssize_t on Python 3315 _Py_ssize_t = ctypes.c_ssize_t316317 # regular python318 class _PyObject(ctypes.Structure):319 pass320 _PyObject._fields_ = [321 ('ob_refcnt', _Py_ssize_t),322 ('ob_type', ctypes.POINTER(_PyObject))323 ]324325 # python with trace326 if hasattr(sys, 'getobjects'):327 class _PyObject(ctypes.Structure):328 pass329 _PyObject._fields_ = [330 ('_ob_next', ctypes.POINTER(_PyObject)),331 ('_ob_prev', ctypes.POINTER(_PyObject)),332 ('ob_refcnt', _Py_ssize_t),333 ('ob_type', ctypes.POINTER(_PyObject))242 class _CTraceback(ctypes.Structure):243 _fields_ = [244 # Extra PyObject slots when compiled with Py_TRACE_REFS.245 (246 "PyObject_HEAD",247 ctypes.c_byte * (32 if hasattr(sys, "getobjects") else 16),248 ),249 # Only care about tb_next as an object, not a traceback.250 ("tb_next", ctypes.py_object),251 ]252336 class _Traceback(_PyObject):337 pass338 _Traceback._fields_ = [339 ('tb_next', ctypes.POINTER(_Traceback)),340 ('tb_frame', ctypes.POINTER(_PyObject)),341 ('tb_lasti', ctypes.c_int),342 ('tb_lineno', ctypes.c_int)343 ]253 def tb_set_next(tb, tb_next):254 c_tb = _CTraceback.from_address(id(tb))255345 def tb_set_next(tb, next):346 """Set the tb_next attribute of a traceback object."""347 if not (isinstance(tb, TracebackType) and348 (next is None or isinstance(next, TracebackType))):349 raise TypeError('tb_set_next arguments must be traceback objects')350 obj = _Traceback.from_address(id(tb))256 # Clear out the old tb_next.257 if tb.tb_next is not None:352 old = _Traceback.from_address(id(tb.tb_next))353 old.ob_refcnt -= 1354 if next is None:355 obj.tb_next = ctypes.POINTER(_Traceback)()356 else:357 next = _Traceback.from_address(id(next))358 next.ob_refcnt += 1359 obj.tb_next = ctypes.pointer(next)258 c_tb_next = ctypes.py_object(tb.tb_next)259 c_tb.tb_next = ctypes.py_object()260 ctypes.pythonapi.Py_DecRef(c_tb_next)261361 return tb_set_next262 # Assign the new tb_next.263 if tb_next is not None:264 c_tb_next = ctypes.py_object(tb_next)265 ctypes.pythonapi.Py_IncRef(c_tb_next)266 c_tb.tb_next = c_tb_next267363364# try to get a tb_set_next implementation if we don't have transparent365# proxies.366tb_set_next = None367if tproxy is None:368 # traceback.tb_next can be modified since CPython 3.7369 if sys.version_info >= (3, 7):370 def tb_set_next(tb, next):371 tb.tb_next = next372 else:373 # On Python 3.6 and older, use ctypes374 try:375 tb_set_next = _init_ugly_crap()376 except Exception:377 pass378del _init_ugly_crap268 return tb
modified:jinja2/environment.py+11 added-42 removed
34 unmodified lines
3536# for direct template usage we have up to ten living environments37_spontaneous_environments = LRUCache(10)3839# the function to create jinja traceback objects. This is dynamically40# imported on the first exception in the exception handler.41_make_traceback = None394340def get_spontaneous_environment(cls, *args):41 """Return a new spontaneous environment. A spontaneous environment42 is used for templates created directly rather than through an43 existing environment.
202 unmodified lines
246 #: shared environments have this set to `True`. A shared environment247 #: must not be modified248 shared = False249254 #: these are currently EXPERIMENTAL undocumented features.255 exception_handler = None256 exception_formatter = None257250 #: the class that is used for code generation. See251 #: :class:`~jinja2.compiler.CodeGenerator` for more information.252 code_generator_class = CodeGenerator253
230 unmodified lines
484 """485 try:486 return self._parse(source, name, filename)487 except TemplateSyntaxError:496 exc_info = sys.exc_info()497 self.handle_exception(exc_info, source_hint=source)488 self.handle_exception(source=source)489490 def _parse(self, source, name, filename):491 """Internal parsing function used by `parse` and `compile`."""492 return Parser(self, source, name, encode_filename(filename)).parse()
11 unmodified lines
504 source = text_type(source)505 try:506 return self.lexer.tokeniter(source, name, filename)507 except TemplateSyntaxError:517 exc_info = sys.exc_info()518 self.handle_exception(exc_info, source_hint=source)508 self.handle_exception(source=source)509510 def preprocess(self, source, name=None, filename=None):511 """Preprocesses the source with all extensions. This is automatically512 called for all parsing and compiling methods but *not* for :meth:`lex`
67 unmodified lines
580 else:581 filename = encode_filename(filename)582 return self._compile(source, filename)583 except TemplateSyntaxError:594 exc_info = sys.exc_info()595 self.handle_exception(exc_info, source_hint=source_hint)584 self.handle_exception(source=source_hint)585586 def compile_expression(self, source, undefined_to_none=True):587 """A handy helper method that returns a callable that accepts keyword588 arguments that appear as variables in the expression. If called it
22 unmodified lines
611612 .. versionadded:: 2.1613 """614 parser = Parser(self, source, state='variable')626 exc_info = None615 try:616 expr = parser.parse_expression()617 if not parser.stream.eos:618 raise TemplateSyntaxError('chunk after expression',619 parser.stream.current.lineno,620 None, None)621 expr.set_environment(self)622 except TemplateSyntaxError:635 exc_info = sys.exc_info()636 if exc_info is not None:637 self.handle_exception(exc_info, source_hint=source)623 if sys.exc_info() is not None:624 self.handle_exception(source=source)625626 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]627 template = self.from_string(nodes.Template(body, lineno=1))628 return TemplateExpression(template, undefined_to_none)629
118 unmodified lines
748 if filter_func is not None:749 x = list(ifilter(filter_func, x))750 return x751764 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):752 def handle_exception(self, source=None):753 """Exception handling helper. This is used internally to either raise754 rewritten exceptions or return a rendered traceback for the template.755 """768 global _make_traceback769 if exc_info is None:770 exc_info = sys.exc_info()756 from jinja2.debug import rewrite_traceback_stack757 reraise(*rewrite_traceback_stack(source=source))758772 # the debugging module is imported when it's used for the first time.773 # we're doing a lot of stuff there and for applications that do not774 # get any exceptions in template rendering there is no need to load775 # all of that.776 if _make_traceback is None:777 from jinja2.debug import make_traceback as _make_traceback778 traceback = _make_traceback(exc_info, source_hint)779 if rendered and self.exception_formatter is not None:780 return self.exception_formatter(traceback)781 if self.exception_handler is not None:782 self.exception_handler(traceback)783 exc_type, exc_value, tb = traceback.standard_exc_info784 reraise(exc_type, exc_value, tb)785759 def join_path(self, template, parent):760 """Join a template with the parent. By default all the lookups are761 relative to the loader root so this method returns the `template`762 parameter unchanged, but if the paths should be relative to the
222 unmodified lines
985 vars = dict(*args, **kwargs)986 try:987 return concat(self.root_render_func(self.new_context(vars)))988 except Exception:1016 exc_info = sys.exc_info()1017 return self.environment.handle_exception(exc_info, True)989 self.environment.handle_exception()990991 def render_async(self, *args, **kwargs):992 """This works similar to :meth:`render` but returns a coroutine993 that when awaited returns the entire rendered template string. This
25 unmodified lines
1019 try:1020 for event in self.root_render_func(self.new_context(vars)):1021 yield event1022 except Exception:1051 exc_info = sys.exc_info()1052 else:1053 return1054 yield self.environment.handle_exception(exc_info, True)1023 yield self.environment.handle_exception()10241025 def generate_async(self, *args, **kwargs):1026 """An async version of :meth:`generate`. Works very similarly but1027 returns an async iterator instead.
229 unmodified lines
modified:jinja2/nativetypes.py+1 added-4 removed
1import sys1import types2from ast import literal_eval3from itertools import islice, chain4from jinja2 import nodes
95 unmodified lines
100 return native_concat(101 self.root_render_func(self.new_context(vars)), preserve_quotes=False102 )103 except Exception:105 exc_info = sys.exc_info()104 return self.environment.handle_exception()105107 return self.environment.handle_exception(exc_info, True)106109107NativeEnvironment.template_class = NativeTemplate
modified:tests/test_debug.py+2 added-2 removed
69 unmodified lines
70(jinja2\.exceptions\.)?TemplateSyntaxError: wtf71 line 42''')7273 def test_local_extraction(self):74 from jinja2.debug import get_jinja_locals74 from jinja2.debug import get_template_locals75 from jinja2.runtime import missing76 locals = get_jinja_locals({76 locals = get_template_locals({77 'l_0_foo': 42,78 'l_1_foo': 23,79 'l_2_foo': 13,80 'l_0_bar': 99,
8 unmodified lines
modified:CHANGES.rst+4 added
79 unmodified lines
80- When chained comparisons of constants are evaluated at compile time,81 the result follows Python's behavior of returning ``False`` if any82 comparison returns ``False``, rather than only the last one.83 :issue:`1102`84- Tracebacks for exceptions in templates show the correct line numbers85 and source for Python >= 3.7. :issue:`1104`86- Tracebacks for template syntax errors in Python 3 no longer show87 internal compiler frames. :issue:`763`888990Version 2.10.391--------------
629 unmodified lines