Skip to content
Myr

[svn] added "debugger of awesomeness" :D

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 17d3b3d · Browse files · 11 files+368 added−155 removed
This commit

State

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

Diff stats

11 files+368 added−155 removed

  • tests:+20 added−2 removed
  • other:+348 added−153 removed

11 files+368 added−155 removed

modified:docs/src/i18n.txt+36 added-4 removed
48 unmodified lines
49 env = ApplicationEnvironment()50 tmpl = env.get_template('index.html')51 tmpl.render(LANGUAGE='de_DE')5253This example assumes that you use gettext and have a gettext54`Translations` object which is returned by the `get_translator`55function.53This example assumes that you use gettext and have a gettext `Translations`54object which is returned by the `get_translator` function. But you don't55have to use gettext. The only thing Jinja requires is an object with to56functions/methods on it that return and accept unicode strings:57``gettext(string)`` that takes a string, translates and returns it, a58``ngettext(singular, plural, count)`` function that returns the correct plural59form for `count` items. Because some languages have no or multiple plural60forms this is necessary.616263Translator Factory64==================6566With Jinja 1.2 onwards it's possible to use a translator factory67instead of an enviornment subclass to create a translator for a context.68A translator factory is passed a context and has to return a translator.69Because of the way classes work you can also assign a translator class70that takes a context object as only argument as factory.7172Example:7374.. sourcecode:: python7576 from jinja import Environment77 from myapplication import get_translator7879 def translator_factory(context):80 return get_translator(context['LANGUAGE'])8182 env = ApplicationEnvironment(translator_factory=translator_factory)83 tmpl = env.get_template('index.html')84 tmpl.render(LANGUAGE='de_DE')8586This example assumes that the translator returned by `get_translator`87already has a gettext and ngettext function that returns unicode strings.888990Collecting Translations91=======================9293The next step is to collect the translations. Every Jinja environment
4 unmodified lines
9899.. sourcecode:: pycon100101 >>> env.get_translations('index.html')70 [(1, u'foo', None), (2, u'Foo', None), (3, u'%d Foo', u'%d Foos')]102 [(1, u'foo', None), (2, u'Foo', None), (3, u'%(count)s Foo', u'%(count)s Foos')]103104The first item in the tuple is the linenumer, the second one is the105singular form and the third is the plural form if given.106
7 unmodified lines
modified:jinja/translators/python.py+10 added-11 removed
41 unmodified lines
42from jinja.parser import Parser43from jinja.exceptions import TemplateSyntaxError44from jinja.translators import Translator45from jinja.datastructure import TemplateStream46from jinja.utils import set, translate_exception, capture_generator, \47 RUNTIME_EXCEPTION_OFFSET46from jinja.utils import set, capture_generator474849#: regular expression for the debug symbols50_debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '
84 unmodified lines
135136 def _debug(self, ctx, exc_type, exc_value, traceback):137 """Debugging Helper"""138 # just modify traceback if we have that feature enabled139 from traceback import print_exception140 print_exception(exc_type, exc_value, traceback)141142 if self.environment.friendly_traceback:141 # debugging system:142 # on any exception we first skip the internal frames (currently143 # either one (python2.5) or two (python2.4 and lower)). After that144 # we call a function that creates a new traceback that is easier145 # to debug.146 for _ in xrange(RUNTIME_EXCEPTION_OFFSET):147 traceback = traceback.tb_next148 traceback = translate_exception(self, exc_type, exc_value,149 traceback, ctx)143 # hook the debugger in144 from jinja.debugger import translate_exception145 exc_type, exc_value, traceback = translate_exception(146 self, ctx, exc_type, exc_value, traceback)147 print_exception(exc_type, exc_value, traceback)148149 raise exc_type, exc_value, traceback150151152class PythonTranslator(Translator):
1059 unmodified lines
added:jinja/_debugger.c+54 added
1/**2 * Jinja Extended Debugger3 * ~~~~~~~~~~~~~~~~~~~~~~~4 *5 * this module allows the jinja debugger to set the tb_next flag6 * on traceback objects. This is required to inject a traceback into7 * another one.8 *9 * :copyright: 2007 by Armin Ronacher.10 * :license: BSD, see LICENSE for more details.11 */1213#include <Python.h>141516/**17 * set the tb_next attribute of a traceback object18 */19PyObject*20tb_set_next(PyObject *self, PyObject *args)21{22 PyObject *tb, *next;2324 if (!PyArg_ParseTuple(args, "OO", &tb, &next))25 return NULL;26 if (!(PyTraceBack_Check(tb) && (PyTraceBack_Check(next) || next == Py_None))) {27 PyErr_SetString(PyExc_TypeError, "traceback object required.");28 return NULL;29 }3031 ((PyTracebackObject*)tb)->tb_next = next;3233 Py_INCREF(Py_None);34 return Py_None;35}363738static PyMethodDef module_methods[] = {39 {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS,40 "Set the tb_next member of a traceback object."},41 {NULL, NULL, 0, NULL} /* Sentinel */42};434445#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */46#define PyMODINIT_FUNC void47#endif48PyMODINIT_FUNC49init_debugger(void)50{51 PyObject *module = Py_InitModule3("_debugger", module_methods, "");52 if (!module)53 return;54}
added:jinja/debugger.py+167 added
1# -*- coding: utf-8 -*-2"""3 jinja.debugger4 ~~~~~~~~~~~~~~56 The debugger module of awesomeness.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import sys13from random import randrange14from opcode import opmap15from types import CodeType1617# if we have extended debugger support we should really use it18try:19 from jinja._debugger import *20 has_extended_debugger = True21except ImportError:22 has_extended_debugger = False2324# we need the RUNTIME_EXCEPTION_OFFSET to skip the not used frames25from jinja.utils import RUNTIME_EXCEPTION_OFFSET262728def fake_template_exception(exc_type, exc_value, traceback, filename, lineno,29 source, context_or_env):30 """31 Raise an exception "in a template". Return a traceback32 object. This is used for runtime debugging, not compile time.33 """34 # some traceback systems allow to skip frames35 __traceback_hide__ = True3637 # create the namespace which will be the local namespace38 # of the new frame then. Some debuggers show local variables39 # so we better inject the context and not the evaluation loop context.40 from jinja.datastructure import Context41 if isinstance(context_or_env, Context):42 env = context_or_env.environment43 namespace = context_or_env.to_dict()44 else:45 env = context_or_env46 namespace = {}4748 # no unicode for filenames49 if isinstance(filename, unicode):50 filename = filename.encode('utf-8')5152 # generate an jinja unique filename used so that linecache53 # gets data that doesn't interferes with other modules54 if filename is None:55 vfilename = 'jinja://~%d' % randrange(0, 10000)56 filename = '<string>'57 else:58 vfilename = 'jinja://%s' % filename5960 # now create the used loaded and update the linecache61 loader = TracebackLoader(env, source, filename)62 loader.update_linecache(vfilename)63 globals = {64 '__name__': vfilename,65 '__file__': vfilename,66 '__loader__': loader67 }6869 # use the simple debugger to reraise the exception in the70 # line where the error originally occoured71 globals['__exception_to_raise__'] = (exc_type, exc_value)72 offset = '\n' * (lineno - 1)73 code = compile(offset + 'raise __exception_to_raise__[0], '74 '__exception_to_raise__[1]',75 vfilename or '<template>', 'exec')76 try:77 exec code in globals, namespace78 except:79 exc_info = sys.exc_info()8081 # if we have an extended debugger we set the tb_next flag82 if has_extended_debugger and traceback is not None:83 tb_set_next(exc_info[2].tb_next, traceback.tb_next)8485 # otherwise just return the exc_info from the simple debugger86 return exc_info878889def translate_exception(template, context, exc_type, exc_value, traceback):90 """91 Translate an exception and return the new traceback.92 """93 # depending on the python version we have to skip some frames to94 # step to get the frame of the current template. The frames before95 # are the toolchain used to render that thing.96 for x in xrange(RUNTIME_EXCEPTION_OFFSET):97 traceback = traceback.tb_next9899 # the next thing we do is matching the current error line against the100 # debugging table to get the correct source line. If we can't find the101 # filename and line number we return the traceback object unaltered.102 error_line = traceback.tb_lineno103 for code_line, tmpl_filename, tmpl_line in template._debug_info[::-1]:104 if code_line <= error_line:105 break106 else:107 return traceback108109 return fake_template_exception(exc_type, exc_value, traceback,110 tmpl_filename, tmpl_line,111 template._source, context)112113114def raise_syntax_error(exception, env, source=None):115 """116 This method raises an exception that includes more debugging117 informations so that debugging works better. Unlike118 `translate_exception` this method raises the exception with119 the traceback.120 """121 exc_info = fake_template_exception(exception, None, None,122 exception.filename,123 exception.lineno, source, env)124 raise exc_info[0], exc_info[1], exc_info[2]125126127class TracebackLoader(object):128 """129 Fake importer that just returns the source of a template.130 """131132 def __init__(self, environment, source, filename):133 self.loader = environment.loader134 self.source = source135 self.filename = filename136137 def update_linecache(self, virtual_filename):138 """139 Hacky way to let traceback systems know about the140 Jinja template sourcecode. Very hackish indeed.141 """142 # check for linecache, not every implementation of python143 # might have such an module.144 try:145 from linecache import cache146 except ImportError:147 return148 data = self.get_source(None)149 cache[virtual_filename] = (150 len(data),151 None,152 data.splitlines(True),153 virtual_filename154 )155156 def get_source(self, impname):157 source = ''158 if self.source is not None:159 source = self.source160 elif self.loader is not None:161 try:162 source = self.loader.get_source(self.filename)163 except TemplateNotFound:164 pass165 if isinstance(source, unicode):166 source = source.encode('utf-8')167 return source
modified:jinja/environment.py+42 added-2 removed
50 unmodified lines
51 filters=None,52 tests=None,53 context_class=Context,54 undefined_singleton=SilentUndefined,55 friendly_traceback=True):55 friendly_traceback=True,56 translator_factory=None):57 """58 Here the possible initialization parameters:5960 ========================= ============================================
49 unmodified lines
110 that shows the error in the template line.111 This however can be annoying when debugging112 broken functions that are called from the113 template. *new in Jinja 1.1*114 `translator_factory` A callback function that is called with115 the context as first argument to get the116 translator for the current instance.117 *new in Jinja 1.2*118 ========================= ============================================119120 All of these variables except those marked with a star (*) are121 modifiable after environment initialization.
32 unmodified lines
154 if auto_escape:155 self.default_filters.append(('escape', (True,)))156 self.globals['Markup'] = Markup157158 # and here the translator factory159 self.translator_factory = translator_factory160161 # create lexer162 self.lexer = Lexer(self)163164 def loader(self, value):
37 unmodified lines
202 except TemplateSyntaxError, e:203 # on syntax errors rewrite the traceback if wanted204 if not self.friendly_traceback:205 raise198 from jinja.utils import raise_syntax_error206 from jinja.debugger import raise_syntax_error207 __traceback_hide__ = True208 raise_syntax_error(e, self, source)209 else:210 # everything went well. attach the source and return it
33 unmodified lines
244 A translator is an object that provides the two functions245 ``gettext(string)`` and ``ngettext(singular, plural, n)``. Note246 that both of them have to return unicode!247 """248 if self.translator_factory is not None:249 return self.translator_factory(context)250 return FakeTranslator()251252 def get_translations(self, name):253 """
13 unmodified lines
267 def apply_filters(self, value, context, filters):268 """269 Apply a list of filters on the variable.270 """271 # some traceback systems allow to skip frames. but allow272 # disabling that via -O to not make things slow273 if __debug__:274 __traceback_hide__ = True275276 cache = context.cache277 for key in filters:278 if key in cache:279 func = cache[key]
8 unmodified lines
288 def perform_test(self, context, testname, args, value, invert):289 """290 Perform a test on a variable.291 """292 # some traceback systems allow to skip frames. but allow293 # disabling that via -O to not make things slow294 if __debug__:295 __traceback_hide__ = True296297 key = (testname, args)298 if key in context.cache:299 func = context.cache[key]300 else:
8 unmodified lines
309 def get_attribute(self, obj, name):310 """311 Get one attribute from an object.312 """313 # some traceback systems allow to skip frames. but allow314 # disabling that via -O to not make things slow315 if __debug__:316 __traceback_hide__ = True317318 try:319 return obj[name]320 except (TypeError, KeyError, IndexError, AttributeError):321 try:
18 unmodified lines
340 """341 Function call helper. Called for all functions that are passed342 any arguments.343 """344 # some traceback systems allow to skip frames. but allow345 # disabling that via -O to not make things slow346 if __debug__:347 __traceback_hide__ = True348349 if dyn_args is not None:350 args += tuple(dyn_args)351 if dyn_kwargs is not None:352 kwargs.update(dyn_kwargs)
8 unmodified lines
361 """362 Function call without arguments. Because of the smaller signature and363 fewer logic here we have a bit of redundant code.364 """365 # some traceback systems allow to skip frames. but allow366 # disabling that via -O to not make things slow367 if __debug__:368 __traceback_hide__ = True369370 if _getattr(f, 'jinja_unsafe_call', False) or \371 _getattr(f, 'alters_data', False):372 return self.undefined_singleton373 if _getattr(f, 'jinja_context_callable', False):
5 unmodified lines
379 As long as no write_var function is passed to the template380 evaluator the source generated by the python translator will381 call this function for all variables.382 """383 # some traceback systems allow to skip frames. but allow384 # disabling that via -O to not make things slow385 if __debug__:386 __traceback_hide__ = True387388 if value is None:389 return u''390 elif value is self.undefined_singleton:391 return unicode(value)
6 unmodified lines
modified:jinja/loaders.py+2 added-1 removed
15 unmodified lines
16from threading import Lock17from jinja.parser import Parser18from jinja.translators.python import PythonTranslator, Template19from jinja.exceptions import TemplateNotFound, TemplateSyntaxError20from jinja.utils import CacheDict, raise_syntax_error20from jinja.utils import CacheDict212223#: when updating this, update the listing in the jinja package too24__all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',
70 unmodified lines
95 except TemplateSyntaxError, e:96 if not self.environment.friendly_traceback:97 raise98 __traceback_hide__ = True99 from jinja.debugger import raise_syntax_error100 raise_syntax_error(e, self.environment)101102 def _loader_missing(self, *args, **kwargs):103 """Helper method that overrides all other methods if no
628 unmodified lines
modified:jinja/utils.py+9 added-128 removed
66 unmodified lines
67 if reverse:68 rv.reverse()69 return rv7071# if we have extended debugger support we should really use it72try:73 from jinja._tbtools import *74 has_extended_debugger = True75except ImportError:76 has_extended_debugger = False7778#: function types79callable_types = (FunctionType, MethodType)8081#: number of maximal range items
250 unmodified lines
332 """333 if 0: yield None334335329def fake_template_exception(exception, filename, lineno, source,330 context_or_env):331 """332 Raise an exception "in a template". Return a traceback333 object. This is used for runtime debugging, not compile time.334 """335 # some traceback systems allow to skip frames336 __traceback_hide__ = True337338 from jinja.datastructure import Context339 if isinstance(context_or_env, Context):340 env = context_or_env.environment341 namespace = context_or_env.to_dict()342 else:343 env = context_or_env344 namespace = {}345346 # generate an jinja unique filename used so that linecache347 # gets data that doesn't interferes with other modules348 if filename is None:349 from random import randrange350 vfilename = 'jinja://~%d' % randrange(0, 10000)351 filename = '<string>'352 else:353 vfilename = 'jinja://%s' % filename354355 offset = '\n' * (lineno - 1)356 code = compile(offset + 'raise __exception_to_raise__',357 vfilename or '<template>', 'exec')358359 loader = TracebackLoader(env, source, filename)360 loader.update_linecache(vfilename)361 globals = {362 '__name__': vfilename,363 '__file__': vfilename,364 '__loader__': loader,365 '__exception_to_raise__': exception366 }367 try:368 exec code in globals, namespace369 except:370 return sys.exc_info()371372373def translate_exception(template, exc_type, exc_value, traceback, context):374 """375 Translate an exception and return the new traceback.376 """377 error_line = traceback.tb_lineno378 for code_line, tmpl_filename, tmpl_line in template._debug_info[::-1]:379 if code_line <= error_line:380 break381 else:382 # no debug symbol found. give up383 return traceback384385 return fake_template_exception(exc_value, tmpl_filename, tmpl_line,386 template._source, context)[2]387388389def raise_syntax_error(exception, env, source=None):390 """391 This method raises an exception that includes more debugging392 informations so that debugging works better. Unlike393 `translate_exception` this method raises the exception with394 the traceback.395 """396 exc_info = fake_template_exception(exception, exception.filename,397 exception.lineno, source, env)398 raise exc_info[0], exc_info[1], exc_info[2]399400336def collect_translations(ast):337 """338 Collect all translatable strings for the given ast. The339 return value is a list of tuples in the form ``(lineno, singular,
8 unmodified lines
348 result.append((node.lineno, node.singular, node.plural))349 elif node.__class__ is CallFunc and \350 node.node.__class__ is Name and \351 node.node.name == '_':417 if len(node.args) in (1, 3):418 args = []419 for arg in node.args:420 if not arg.__class__ is Const:421 break422 args.append(arg.value)423 else:424 if len(args) == 1:425 singular = args[0]426 plural = None427 else:428 singular, plural, _ = args429 result.append((node.lineno, singular, plural))352 if len(node.args) == 1 and node.args[0].__class__ is Const:353 result.append((node.lineno, node.args[0].value, None))354 todo.extend(node.getChildNodes())355 result.sort(lambda a, b: cmp(a[0], b[0]))356 return result357
57 unmodified lines
415#: the singleton instance of `DebugHelper`416debug_helper = object.__new__(DebugHelper)417418495class TracebackLoader(object):496 """497 Fake importer that just returns the source of a template.498 """499500 def __init__(self, environment, source, filename):501 self.loader = environment.loader502 self.source = source503 self.filename = filename504505 def update_linecache(self, virtual_filename):506 """507 Hacky way to let traceback systems know about the508 Jinja template sourcecode. Very hackish indeed.509 """510 # check for linecache, not every implementation of python511 # might have such an module.512 try:513 from linecache import cache514 except ImportError:515 return516 data = self.get_source(None)517 cache[virtual_filename] = (518 len(data),519 None,520 data.splitlines(True),521 virtual_filename522 )523524 def get_source(self, impname):525 source = ''526 if self.source is not None:527 source = self.source528 elif self.loader is not None:529 try:530 source = self.loader.get_source(self.filename)531 except TemplateNotFound:532 pass533 if isinstance(source, unicode):534 source = source.encode('utf-8')535 return source536537419class CacheDict(object):420 """421 A dict like object that stores a limited number of items and forgets422 about the least recently used items::
159 unmodified lines
modified:tests/runtime/exception.py+12 added-2 removed
30 unmodified lines
31 <li><a href="syntax_error">syntax error</a></li>32 <li><a href="runtime_error">runtime error</a></li>33 <li><a href="nested_syntax_error">nested syntax error</a></li>34 <li><a href="nested_runtime_error">nested runtime error</a></li>35 <li><a href="code_runtime_error">runtime error in code</a></li>36 <li><a href="syntax_from_string">a syntax error from string</a></li>37 <li><a href="runtime_from_string">runtime error from a string</a></li>38 </ul>39 </body>
13 unmodified lines
53 '/nested_syntax_error': u'''54{% include 'syntax_broken' %}55 ''',5657 '/code_runtime_error': u'''58{{ broken() }}59''',6061 'runtime_broken': '''\62This is an included template63{% set a = 1 / 0 %}''',64 'syntax_broken': '''\
4 unmodified lines
69FAILING_STRING_TEMPLATE = '{{ 1 / 0 }}'70BROKEN_STRING_TEMPLATE = '{% if foo %}...{% endfor %}'717273def broken():74 raise RuntimeError("I'm broken")757677def test(environ, start_response):78 path = environ.get('PATH_INFO' or '/')79 try:80 tmpl = e.get_template(path)
5 unmodified lines
86 else:87 start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])88 return ['NOT FOUND']89 start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])81 return [tmpl.render().encode('utf-8')]90 return [tmpl.render(broken=broken).encode('utf-8')]919293if __name__ == '__main__':84 from colubrid.debug import DebuggedApplication94 from werkzeug.debug import DebuggedApplication95 app = DebuggedApplication(test)96 make_server("localhost", 7000, app).serve_forever()
modified:tests/test_i18n.py+8 added
56 unmodified lines
5758i18n_env = I18NEnvironment()596061def test_factory():62 def factory(context):63 return SimpleTranslator(context['LANGUAGE'] or 'en')64 env = Environment(translator_factory=factory)65 tmpl = env.from_string('{% trans "watch out" %}')66 assert tmpl.render(LANGUAGE='de') == 'pass auf'676869def test_get_translations():70 trans = list(i18n_env.get_translations('child.html'))71 assert len(trans) == 172 assert trans[0] == (1, u'watch out', None)
22 unmodified lines
modified:CHANGES+12 added
1Jinja Changelog2===============34Version 1.25-----------6(codename to be selected, release date unknown)78- environments now have a `translator_factory` parameter that allows9 to change the translator without subclassing the environment.1011- fixed bug in buffet plugin regarding the package loader1213- once again improved debugger.141516Version 1.117-----------18(codename: sinka, released Jun 1, 2007)19
119 unmodified lines
modified:setup.py+16 added-7 removed
76 unmodified lines
77 [python.templating.engines]78 jinja = jinja.plugin:BuffetPlugin79 ''',80 extras_require = {'plugin': ['setuptools>=0.6a2']},81 features = {81 features = {'speedups': Feature(82 'optional C-speed enhancements',83 standard = True,84 ext_modules = [85 Extension('jinja._speedups', ['jinja/_speedups.c'])86 ]87 )},82 'speedups': Feature(83 'optional C-speed enhancements',84 standard = True,85 ext_modules = [86 Extension('jinja._speedups', ['jinja/_speedups.c'])87 ]88 ),89 'extended-debugger': Feature(90 'extended debugger',91 standard = True,92 ext_modules = [93 Extension('jinja._debugger', ['jinja/_debugger.c'])94 ]95 )96 },97 cmdclass = {'build_ext': optional_build_ext}98)