[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
Provenance
- Commit
a7804ef- Tree
882fd10- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
17d3b3d
11 files changed+368 added−155 removed
modified:docs/src/i18n.txt+36 added-4 removed
48 unmodified lines49 env = ApplicationEnvironment()50 tmpl = env.get_template('index.html')51 tmpl.render(LANGUAGE='de_DE')52 53-This example assumes that you use gettext and have a gettext54-`Translations` object which is returned by the `get_translator`55-function.53+This example assumes that you use gettext and have a gettext `Translations`54+object which is returned by the `get_translator` function. But you don't55+have to use gettext. The only thing Jinja requires is an object with to56+functions/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 plural59+form for `count` items. Because some languages have no or multiple plural60+forms this is necessary.61 62 63+Translator Factory64+==================65+66+With Jinja 1.2 onwards it's possible to use a translator factory67+instead of an enviornment subclass to create a translator for a context.68+A translator factory is passed a context and has to return a translator.69+Because of the way classes work you can also assign a translator class70+that takes a context object as only argument as factory.71+72+Example:73+74+.. sourcecode:: python75+76+ from jinja import Environment77+ from myapplication import get_translator78+79+ def translator_factory(context):80+ return get_translator(context['LANGUAGE'])81+82+ env = ApplicationEnvironment(translator_factory=translator_factory)83+ tmpl = env.get_template('index.html')84+ tmpl.render(LANGUAGE='de_DE')85+86+This example assumes that the translator returned by `get_translator`87+already has a gettext and ngettext function that returns unicode strings.88+89+90 Collecting Translations91 =======================92 93 The next step is to collect the translations. Every Jinja environment4 unmodified lines98 99 .. sourcecode:: pycon100 101 >>> 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')]103 104 The first item in the tuple is the linenumer, the second one is the105 singular form and the third is the plural form if given.106 7 unmodified linesmodified:jinja/translators/python.py+10 added-11 removed
41 unmodified lines42 from jinja.parser import Parser43 from jinja.exceptions import TemplateSyntaxError44 from jinja.translators import Translator45 from jinja.datastructure import TemplateStream46-from jinja.utils import set, translate_exception, capture_generator, \47- RUNTIME_EXCEPTION_OFFSET46+from jinja.utils import set, capture_generator47 48 49 #: regular expression for the debug symbols50 _debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '84 unmodified lines135 136 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)141+142 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)148+149 raise exc_type, exc_value, traceback150 151 152 class PythonTranslator(Translator):1059 unmodified linesadded: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+ */12+13+#include <Python.h>14+15+16+/**17+ * set the tb_next attribute of a traceback object18+ */19+PyObject*20+tb_set_next(PyObject *self, PyObject *args)21+{22+ PyObject *tb, *next;23+24+ 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+ }30+31+ ((PyTracebackObject*)tb)->tb_next = next;32+33+ Py_INCREF(Py_None);34+ return Py_None;35+}36+37+38+static 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+};43+44+45+#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */46+#define PyMODINIT_FUNC void47+#endif48+PyMODINIT_FUNC49+init_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+ ~~~~~~~~~~~~~~5+6+ The debugger module of awesomeness.7+8+ :copyright: 2007 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import sys13+from random import randrange14+from opcode import opmap15+from types import CodeType16+17+# if we have extended debugger support we should really use it18+try:19+ from jinja._debugger import *20+ has_extended_debugger = True21+except ImportError:22+ has_extended_debugger = False23+24+# we need the RUNTIME_EXCEPTION_OFFSET to skip the not used frames25+from jinja.utils import RUNTIME_EXCEPTION_OFFSET26+27+28+def 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__ = True36+37+ # 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 = {}47+48+ # no unicode for filenames49+ if isinstance(filename, unicode):50+ filename = filename.encode('utf-8')51+52+ # 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' % filename59+60+ # 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+ }68+69+ # 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()80+81+ # 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)84+85+ # otherwise just return the exc_info from the simple debugger86+ return exc_info87+88+89+def 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_next98+99+ # 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 traceback108+109+ return fake_template_exception(exc_type, exc_value, traceback,110+ tmpl_filename, tmpl_line,111+ template._source, context)112+113+114+def 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]125+126+127+class TracebackLoader(object):128+ """129+ Fake importer that just returns the source of a template.130+ """131+132+ def __init__(self, environment, source, filename):133+ self.loader = environment.loader134+ self.source = source135+ self.filename = filename136+137+ 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+ )155+156+ 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 sourcemodified:jinja/environment.py+42 added-2 removed
50 unmodified lines51 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:59 60 ========================= ============================================49 unmodified lines110 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 ========================= ============================================119 120 All of these variables except those marked with a star (*) are121 modifiable after environment initialization.32 unmodified lines154 if auto_escape:155 self.default_filters.append(('escape', (True,)))156 self.globals['Markup'] = Markup157 158+ # and here the translator factory159+ self.translator_factory = translator_factory160+161 # create lexer162 self.lexer = Lexer(self)163 164 def loader(self, value):37 unmodified lines202 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 it33 unmodified lines244 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()251 252 def get_translations(self, name):253 """13 unmodified lines267 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__ = True275+276 cache = context.cache277 for key in filters:278 if key in cache:279 func = cache[key]8 unmodified lines288 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__ = True296+297 key = (testname, args)298 if key in context.cache:299 func = context.cache[key]300 else:8 unmodified lines309 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__ = True317+318 try:319 return obj[name]320 except (TypeError, KeyError, IndexError, AttributeError):321 try:18 unmodified lines340 """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__ = True348+349 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 lines361 """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__ = True369+370 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 lines379 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__ = True387+388 if value is None:389 return u''390 elif value is self.undefined_singleton:391 return unicode(value)6 unmodified linesmodified:jinja/loaders.py+2 added-1 removed
15 unmodified lines16 from threading import Lock17 from jinja.parser import Parser18 from jinja.translators.python import PythonTranslator, Template19 from jinja.exceptions import TemplateNotFound, TemplateSyntaxError20-from jinja.utils import CacheDict, raise_syntax_error20+from jinja.utils import CacheDict21 22 23 #: when updating this, update the listing in the jinja package too24 __all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',70 unmodified lines95 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)101 102 def _loader_missing(self, *args, **kwargs):103 """Helper method that overrides all other methods if no628 unmodified linesmodified:jinja/utils.py+9 added-128 removed
66 unmodified lines67 if reverse:68 rv.reverse()69 return rv70 71+# if we have extended debugger support we should really use it72+try:73+ from jinja._tbtools import *74+ has_extended_debugger = True75+except ImportError:76+ has_extended_debugger = False77+78 #: function types79 callable_types = (FunctionType, MethodType)80 81 #: number of maximal range items250 unmodified lines332 """333 if 0: yield None334 335 329-def 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__ = True337-338- 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 = {}345-346- # 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' % filename354-355- offset = '\n' * (lineno - 1)356- code = compile(offset + 'raise __exception_to_raise__',357- vfilename or '<template>', 'exec')358-359- 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()371-372-373-def 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 traceback384-385- return fake_template_exception(exc_value, tmpl_filename, tmpl_line,386- template._source, context)[2]387-388-389-def 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]399-400-336 def 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 lines348 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 lines415 #: the singleton instance of `DebugHelper`416 debug_helper = object.__new__(DebugHelper)417 418 495-class TracebackLoader(object):496- """497- Fake importer that just returns the source of a template.498- """499-500- def __init__(self, environment, source, filename):501- self.loader = environment.loader502- self.source = source503- self.filename = filename504-505- 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- )523-524- 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 source536-537-419 class 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 linesmodified:tests/runtime/exception.py+12 added-2 removed
30 unmodified lines31 <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 lines53 '/nested_syntax_error': u'''54 {% include 'syntax_broken' %}55 ''',56 57+ '/code_runtime_error': u'''58+{{ broken() }}59+''',60+61 'runtime_broken': '''\62 This is an included template63 {% set a = 1 / 0 %}''',64 'syntax_broken': '''\4 unmodified lines69 FAILING_STRING_TEMPLATE = '{{ 1 / 0 }}'70 BROKEN_STRING_TEMPLATE = '{% if foo %}...{% endfor %}'71 72 73+def broken():74+ raise RuntimeError("I'm broken")75+76+77 def test(environ, start_response):78 path = environ.get('PATH_INFO' or '/')79 try:80 tmpl = e.get_template(path)5 unmodified lines86 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')]91 92+93 if __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 lines57 58 i18n_env = I18NEnvironment()59 60 61+def 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'67+68+69 def 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 linesmodified:CHANGES+12 added
1 Jinja Changelog2 ===============3 4+Version 1.25+-----------6+(codename to be selected, release date unknown)7+8+- environments now have a `translator_factory` parameter that allows9+ to change the translator without subclassing the environment.10+11+- fixed bug in buffet plugin regarding the package loader12+13+- once again improved debugger.14+15+16 Version 1.117 -----------18 (codename: sinka, released Jun 1, 2007)19 119 unmodified linesmodified:setup.py+16 added-7 removed
76 unmodified lines77 [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 )