[svn] improved jinja debugging system. now handles errors in included templates too
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 94dd3d0 · Browse files · 7 files·+88 added−43 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+88 added−43 removed
- tests:+4 added−2 removed
- other:+84 added−41 removed
Provenance
- Commit
18b3d0b- Tree
18badf1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
94dd3d0
7 files changed+88 added−43 removed
modified:docs/src/objects.txt+4 added
85 unmodified lines86 87 class MyModel(...):88 89 # just give access to a and b. Default is all90+ # note that this also disallows the functions from below.91+ # if you use jinja_allowed_attributes you don't have to92+ # do the code below because methods are threaded as attributes93+ # too.94 jinja_allowed_attributes = ['a', 'b']95 96 def __init__(self, ...):97 ...17 unmodified linesmodified:jinja/translators/python.py+61 added-30 removed
37 unmodified lines38 self.code = code39 self.translated_source = translated_source40 self.generate_func = None41 42- def source(self):43- """The original sourcecode for this template."""44- return self.environment.loader.get_source(self.code.co_filename)45- source = property(source, doc=source.__doc__)46-42 def dump(self, stream=None):43 """Dump the template into python bytecode."""44 if stream is not None:45 from marshal import dump123 unmodified lines169 return (' ' * (self.indention * 4)) + text170 171 def nodeinfo(self, node):172 """178- Return a comment that helds the node informations.173+ Return a comment that helds the node informations or None174+ if there is no need to add a debug comment.175 """180- return '# DEBUG(filename=%r, lineno=%s)' % (176+ rv = '# DEBUG(filename=%s, lineno=%s)' % (177 node.filename,178 node.lineno179 )180+ if rv != self.last_debug_comment:181+ self.last_debug_comment = rv182+ return rv183 184 def filter(self, s, filter_nodes):185 """186 Apply a filter on an object that already is a python expression.46 unmodified lines233 234 def reset(self):235 self.indention = 0236 self.last_cycle_id = 0237+ self.last_debug_comment = None238 239 def translate(self):240 self.reset()241 return self.handle_node(self.node)86 unmodified lines328 def handle_template_text(self, node):329 """330 Handle data around nodes.331 """332- return self.indent(self.nodeinfo(node)) + '\n' + \333- self.indent('yield %r' % node.text)332+ nodeinfo = self.nodeinfo(node) or ''333+ if nodeinfo:334+ nodeinfo = self.indent(nodeinfo) + '\n'335+ return nodeinfo + self.indent('yield %r' % node.text)336 337 def handle_node_list(self, node):338 """339 In some situations we might have a node list. It's just340 a collection of multiple statements.341 """342 buf = [self.handle_node(n) for n in node]343 if buf:342- return '\n'.join([self.indent(self.nodeinfo(node))] + buf)343- return ''344+ nodeinfo = self.nodeinfo(node)345+ if nodeinfo:346+ buf = [self.indent(nodeinfo)] + buf347+ return '\n'.join(buf)348 349 def handle_for_loop(self, node):350 """351 Handle a for loop. Pretty basic, just that we give the else352 clause a different behavior.353 """354 buf = []355 write = lambda x: buf.append(self.indent(x))352- write(self.nodeinfo(node))356+ nodeinfo = self.nodeinfo(node)357+ if nodeinfo:358+ write(nodeinfo)359 write('ctx_push()')360 361 # recursive loops362 if node.recursive:12 unmodified lines375 )376 377 # handle real loop code378 self.indention += 1373- buf.append(self.indent(self.nodeinfo(node.body)))379+ nodeinfo = self.nodeinfo(node.body)380+ if nodeinfo:381+ write(nodeinfo)382 buf.append(self.handle_node(node.body))383 self.indention -= 1384 385 # else part of loop386 if node.else_:387 write('if not context[\'loop\'].iterated:')388 self.indention += 1381- buf.append(self.indent(self.nodeinfo(node.else_)))389+ nodeinfo = self.nodeinfo(node.else_)390+ if nodeinfo:391+ write(nodeinfo)392 buf.append(self.handle_node(node.else_))393 self.indention -= 1394 395 # call recursive for loop!17 unmodified lines413 Handle an if condition node.414 """415 buf = []416 write = lambda x: buf.append(self.indent(x))407- write(self.nodeinfo(node))417+ nodeinfo = self.nodeinfo(node)418+ if nodeinfo:419+ write(nodeinfo)420 for idx, (test, body) in enumerate(node.tests):421 write('%sif %s:' % (422 idx and 'el' or '',423 self.handle_node(test)424 ))425 self.indention += 1414- write(self.nodeinfo(node))426+ nodeinfo = self.nodeinfo(body)427+ if nodeinfo:428+ write(nodeinfo)429 buf.append(self.handle_node(body))430 self.indention -= 1431 if node.else_ is not None:432 write('else:')433 self.indention += 1420- write(self.nodeinfo(node))434+ nodeinfo = self.nodeinfo(node.else_)435+ if nodeinfo:436+ write(nodeinfo)437 buf.append(self.handle_node(node.else_))438 self.indention -= 1439 return '\n'.join(buf)440 7 unmodified lines448 write = lambda x: buf.append(self.indent(x))449 450 write('if not %r in context.current:' % name)451 self.indention += 1436- write(self.nodeinfo(node))452+ nodeinfo = self.nodeinfo(node)453+ if nodeinfo:454+ write(nodeinfo)455 if node.seq.__class__ in (ast.Tuple, ast.List):456 write('context.current[%r] = CycleContext(%s)' % (457 name,458 _to_tuple([self.handle_node(n) for n in node.seq.nodes])17 unmodified lines476 def handle_print(self, node):477 """478 Handle a print statement.479 """480+ nodeinfo = self.nodeinfo(node) or ''481+ if nodeinfo:462- return self.indent(self.nodeinfo(node)) + '\n' + \463- self.indent('yield finish_var(%s)' %464- self.handle_node(node.variable))482+ nodeinfo = self.indent(nodeinfo) + '\n'483+ return nodeinfo + self.indent('yield finish_var(%s)' %484+ self.handle_node(node.variable))485 486 def handle_macro(self, node):487 """488 Handle macro declarations.2 unmodified lines491 write = lambda x: buf.append(self.indent(x))492 493 write('def macro(*args):')494 self.indention += 1475- write(self.nodeinfo(node))495+ nodeinfo = self.nodeinfo(node)496+ if nodeinfo:497+ write(nodeinfo)498 499 if node.arguments:500 write('argcount = len(args)')501 tmp = []7 unmodified lines509 write('ctx_push({%s})' % ', '.join(tmp))510 else:511 write('ctx_push()')512 491- write(self.nodeinfo(node.body))513+ nodeinfo = self.nodeinfo(node.body)514+ if nodeinfo:515+ write(nodeinfo)516 buf.append(self.handle_node(node.body))517 write('ctx_pop()')518 write('if False:')519 self.indention += 16 unmodified lines526 def handle_set(self, node):527 """528 Handle variable assignments.529 """506- return self.indent(self.nodeinfo(node)) + '\n' + \507- self.indent('context[%r] = %s' % (530+ nodeinfo = self.nodeinfo(node) or ''531+ if nodeinfo:532+ nodeinfo = self.indent(nodeinfo) + '\n'533+ return nodeinfo + self.indent('context[%r] = %s' % (534 node.name,535 self.handle_node(node.expr)536 ))537 4 unmodified lines542 buf = []543 write = lambda x: buf.append(self.indent(x))544 write('def filtered():')545 self.indention += 1520- write(self.nodeinfo(node))546 write('ctx_push()')522- write(self.nodeinfo(node.body))547+ nodeinfo = self.nodeinfo(node.body)548+ if nodeinfo:549+ write(nodeinfo)550 buf.append(self.handle_node(node.body))551 write('ctx_pop()')552 write('if False:')553 self.indention += 115 unmodified lines569 buf = []570 write = lambda x: buf.append(self.indent(x))571 572 write('ctx_push()')546- write(self.nodeinfo(node.body))573+ nodeinfo = self.nodeinfo(node.body)574+ if nodeinfo:575+ write(nodebody)576 buf.append(self.handle_node(node.body))577 write('ctx_pop()')578 return '\n'.join(buf)579 19 unmodified lines599 ))600 replacements = '{%s}' % ', '.join(replacements)601 else:602 replacements = 'None'574- return self.indent(self.nodeinfo(node)) + '\n' + \575- self.indent('yield translate(%r, %r, %r, %s)' % (603+ nodeinfo = self.nodeinfo(node) or ''604+ if nodeinfo:605+ nodeinfo = self.indent(nodeinfo) + '\n'606+ return nodeinfo + self.indent('yield translate(%r, %r, %r, %s)' % (607 node.singular,608 node.plural,609 node.indicator,610 replacements282 unmodified linesmodified:jinja/utils.py+18 added-10 removed
172 unmodified lines173 return capture_generator(f(*args, **kwargs))174 return wrapped175 176 177-def raise_template_exception(template, exception, filename, lineno, context):177+def raise_template_exception(exception, filename, lineno, context):178 """179 Raise an exception "in a template". Return a traceback180 object.181 """5 unmodified lines187 namespace = context.to_dict()188 globals = {189 '__name__': filename,190 '__file__': filename,191- '__loader__': TracebackLoader(template),191+ '__loader__': TracebackLoader(context.environment,192+ filename),193 '__exception_to_raise__': exception194 }195 try:196 exec code in globals, namespace7 unmodified lines204 Translate an exception and return the new traceback.205 """206 sourcelines = template.translated_source.splitlines()207 startpos = traceback.tb_lineno - 1207- args = None208+ filename = None209 # looks like we loaded the template from string. we cannot210 # do anything here.211 if startpos > len(sourcelines):212 return traceback213 214 while startpos > 0:215 m = _debug_info_re.search(sourcelines[startpos])216 if m is not None:216- args = m.groups()217+ filename, lineno = m.groups()218+ if filename == 'None':219+ filename = ''220+ if lineno == 'None':221+ lineno = 0222+ else:223+ lineno = int(lineno)224 break225 startpos -= 1226 227 # no traceback information found, reraise unchanged221- if args is None:228+ if filename is None:229 return traceback223- return raise_template_exception(template, exc_value, args[0],224- int(args[1] or 0), context)230+ return raise_template_exception(exc_value, filename,231+ lineno, context)232 233 234 class TracebackLoader(object):235 """236 Fake importer that just returns the source of a template.237 """238 232- def __init__(self, template):233- self.template = template239+ def __init__(self, environment, filename):240+ self.loader = environment.loader241+ self.filename = filename242 243 def get_source(self, impname):236- return self.template.source244+ return self.loader.get_source(self.filename)245 246 247 class CacheDict(object):248 """123 unmodified linesmodified:tests/templates/error.html+1 added-1 removed
1234456<ul><meta http-equiv="Content-Type" content="" />{% for item in items %} {{ item + "this will break the application" }} {% include "included_error.html" %}{% endfor %}</ul>added:tests/templates/included_error.html+2 added
12This breaks the template:{{ 1 / 0 }}modified:tests/exception.py+1 added-1 removed
5 unmodified lines6 def test(*args):7 tmpl = e.loader.load('error.html')8 tmpl.render(items=range(10))9 10-make_server("localhost", 7000, DebuggedApplication(test, False)).serve_forever()10+make_server("localhost", 7000, DebuggedApplication(test)).serve_forever()modified:www/static/pygments.css+1 added-1 removed
11234553 unmodified lines.syntax { background: #ffffff; }.syntax { background: #ffffff; }.syntax .c { color: #888888 } /* Comment */.syntax .err { color: #a61717; background-color: #e3d2d2 } /* Error */.syntax .k { color: #008800; font-weight: bold } /* Keyword */.syntax .cm { color: #888888 } /* Comment.Multiline */53 unmodified lines