moved concat to utils, fixed a few docstrings, fixed memory leak in _speedups.escape
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 132757b · Browse files · 12 files·+56 added−54 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+56 added−54 removed
- tests:+3 added−1 removed
- other:+53 added−53 removed
Provenance
- Commit
7ceced5- Tree
b2bd1f1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
132757b
12 files changed+56 added−54 removed
modified:docs/api.rst+1 added-1 removed
83 unmodified lines84 to modify this dict. For more details see :ref:`global-namespace`.85 86 87 .. autoclass:: jinja2.Template88- :members: render, stream, generate, module88+ :members: render, stream, generate, make_module, module89 90 .. attribute:: globals91 92 foo244 unmodified linesmodified:jinja2/_speedups.c+9 added-11 removed
1 /**2 * jinja2._speedups3 * ~~~~~~~~~~~~~~~~4 *5- * This module implements a few functions in C for better performance.5+ * This module implements a few functions in C for better performance. It6+ * also defines a `tb_set_next` function that is used to patch the debug7+ * traceback. If the speedups module is not compiled a ctypes implementation8+ * is used.9 *10 * :copyright: 2008 by Armin Ronacher.11 * :license: BSD.12 */118 unmodified lines131 132 /* we don't have to escape integers, bools or floats */133 if (PyInt_CheckExact(text) || PyLong_CheckExact(text) ||134 PyFloat_CheckExact(text) || PyBool_Check(text) ||132- text == Py_None) {133- PyObject *args = PyTuple_New(1);134- if (!args) {135- Py_DECREF(s);136- return NULL;137- }138- PyTuple_SET_ITEM(args, 0, text);139- return PyObject_CallObject(markup, args);140- }135+ text == Py_None)136+ return PyObject_CallFunctionObjArgs(markup, text, NULL);137 138 /* if the object has an __html__ method that performs the escaping */139 PyObject *html = PyObject_GetAttrString(text, "__html__");140 if (html) {14 unmodified lines155 else156 s = escape_unicode((PyUnicodeObject*)text);157 158 /* convert the unicode string into a markup object. */163- return PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);159+ rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);160+ Py_DECREF(s);161+ return rv;162 }163 164 165 static PyObject *53 unmodified linesmodified:jinja2/compiler.py+1 added-2 removed
15 unmodified lines16 from itertools import chain17 from jinja2 import nodes18 from jinja2.visitor import NodeVisitor, NodeTransformer19 from jinja2.exceptions import TemplateAssertionError20-from jinja2.runtime import concat21-from jinja2.utils import Markup20+from jinja2.utils import Markup, concat21 22 23 operators = {24 'eq': '==',1218 unmodified linesmodified:jinja2/environment.py+8 added-5 removed
12 unmodified lines13 from jinja2.lexer import Lexer14 from jinja2.parser import Parser15 from jinja2.optimizer import optimize16 from jinja2.compiler import generate17-from jinja2.runtime import Undefined, Context, concat17+from jinja2.runtime import Undefined, Context18 from jinja2.debug import translate_exception, translate_syntax_error19 from jinja2.exceptions import TemplateSyntaxError20-from jinja2.utils import import_string, LRUCache, Markup, missing20+from jinja2.utils import import_string, LRUCache, Markup, missing, concat21 22 23 # for direct template usage we have up to ten living environments24 _spontaneous_environments = LRUCache(10)504 unmodified lines529 parent = dict(self.globals, **vars)530 return Context(self.environment, parent, self.name, self.blocks)531 532 def make_module(self, vars=None, shared=False):533- """Like the `module` property but always reevaluates the template534- and it's possible to provide a context.533+ """This method works like the :attr:`module` attribute when called534+ without arguments but it will evaluate the template every call535+ rather then caching the template. It's also possible to provide536+ a dict which is then used as context. The arguments are the same537+ as fo the :meth:`new_context` method.538 """539 return TemplateModule(self, self.new_context(vars, shared))540 541 @property53 unmodified lines595 # don't alter this attribute unless you change it in the596 # compiler too. The Include without context passing directly597 # uses the mangled name. The reason why we use a mangled one598 # is to avoid name clashes with macros with those names.596- self.__body_stream = tuple(template.root_render_func(context))599+ self.__body_stream = list(template.root_render_func(context))600 self.__dict__.update(context.get_exported())601 self.__name__ = template.name602 603 __html__ = lambda x: Markup(concat(x.__body_stream))70 unmodified linesmodified:jinja2/filters.py+1 added-5 removed
9 unmodified lines10 """11 import re12 import math13 from random import choice14-try:15- from operator import itemgetter14+from operator import itemgetter16-except ImportError:17- itemgetter = lambda a: lambda b: b[a]18-from urllib import urlencode, quote15 from itertools import imap, groupby16 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode17 from jinja2.runtime import Undefined18 from jinja2.exceptions import FilterArgumentError651 unmodified linesmodified:jinja2/nodes.py+1 added-1 removed
11 unmodified lines12 :copyright: 2008 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14 """15 import operator16+from copy import copy17 from types import FunctionType18 from itertools import chain, izip19 from collections import deque19-from copy import copy20 from jinja2.utils import Markup21 22 23 _binop_to_func = {606 unmodified linesmodified:jinja2/optimizer.py+2 added-1 removed
16 unmodified lines17 :license: GNU GPL.18 """19 from jinja2 import nodes20 from jinja2.visitor import NodeVisitor, NodeTransformer21-from jinja2.runtime import LoopContext, concat21+from jinja2.runtime import LoopContext22+from jinja2.utils import concat23 24 25 def optimize(node, environment, context_hint=None):26 """The context hint can be used to perform an static optimization155 unmodified linesmodified:jinja2/runtime.py+1 added-22 removed
9 unmodified lines10 """11 import sys12 from types import FunctionType13 from itertools import chain, imap14-from jinja2.utils import Markup, partial, soft_unicode, escape, missing14+from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError16 17 18 # these variables are exported to the template runtime1 unmodified line20 'TemplateRuntimeError', 'missing', 'concat', 'escape',21 'markup_join', 'unicode_join']22 23 24-# concatenate a list of strings and convert them to unicode.25-# unfortunately there is a bug in python 2.4 and lower that causes26-# unicode.join trash the traceback.27-try:28- def _test_gen_bug():29- raise TypeError(_test_gen_bug)30- yield None31- u''.join(_test_gen_bug())32-except TypeError, _error:33- if _error.args and _error.args[0] is _test_gen_bug:34- concat = u''.join35- else:36- def concat(gen):37- try:38- return u''.join(list(gen))39- except:40- exc_type, exc_value, tb = sys.exc_info()41- raise exc_type, exc_value, tb.tb_next42- del _test_gen_bug, _error43-44-24 def markup_join(*args):25 """Concatenation that escapes if necessary and converts to unicode."""26 buf = []27 iterator = imap(soft_unicode, args)359 unmodified linesmodified:jinja2/sandbox.py+5 added-3 removed
21 unmodified lines22 23 24 def safe_range(*args):25 """A range that can't generate ranges with a length of more than26- MAX_RANGE items."""26+ MAX_RANGE items.27+ """28 rng = xrange(*args)29 if len(rng) > MAX_RANGE:30 raise OverflowError('range too big')31 return rng29 unmodified lines61 62 def is_safe_callable(self, obj):63 """Check if an object is safely callable. Per default a function is64 considered safe unless the `unsafe_callable` attribute exists and is64- truish. Override this method to alter the behavior, but this won't65+ True. Override this method to alter the behavior, but this won't66 affect the `unsafe` decorator from this module.67 """67- return not getattr(obj, 'unsafe_callable', False)68+ return not (getattr(obj, 'unsafe_callable', False) or \69+ getattr(obj, 'alters_data', False))70 71 def subscribe(self, obj, argument):72 """Subscribe an object from sandboxed code."""73 is_unsafe = False26 unmodified linesmodified:jinja2/utils.py+23 added
31 unmodified lines32 # special singleton representing missing values for the runtime33 missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()34 35 36+# concatenate a list of strings and convert them to unicode.37+# unfortunately there is a bug in python 2.4 and lower that causes38+# unicode.join trash the traceback.39+try:40+ def _test_gen_bug():41+ raise TypeError(_test_gen_bug)42+ yield None43+ u''.join(_test_gen_bug())44+except TypeError, _error:45+ if _error.args and _error.args[0] is _test_gen_bug:46+ concat = u''.join47+ else:48+ def concat(gen):49+ try:50+ return u''.join(list(gen))51+ except:52+ # this hack is needed so that the current frame53+ # does not show up in the traceback.54+ exc_type, exc_value, tb = sys.exc_info()55+ raise exc_type, exc_value, tb.tb_next56+ del _test_gen_bug, _error57+58+59 def contextfunction(f):60 """This decorator can be used to mark a callable as context callable. A61 context callable is passed the active context as first argument if it62 was directly stored in the context.425 unmodified linesmodified:tests/test_imports.py+3 added-1 removed
11 unmodified lines12 test_env = Environment(loader=DictLoader(dict(13 module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',14 header='[{{ foo }}|{{ 23 }}]'15 )))16-test_env.globals['bar'] = '23'16+test_env.globals['bar'] = 2317 18 19 def test_context_imports():20 t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')22 unmodified lines43 def test_trailing_comma():44 test_env.from_string('{% from "foo" import bar, baz with context %}')45 test_env.from_string('{% from "foo" import bar, baz, with context %}')46 test_env.from_string('{% from "foo" import bar, with context %}')47+ test_env.from_string('{% from "foo" import bar, with, context %}')48+ test_env.from_string('{% from "foo" import bar, with with context %}')modified:setup.py+1 added-2 removed
118 unmodified lines119 'Topic :: Text Processing :: Markup :: HTML'120 ],121 packages=['jinja2'],122 data_files=[123- ('docs/html', list(list_files('docs/html'))),124- ('docs/txt', list(list_files('docs/src')))123+ ##('docs', list(list_files('docs/_build/html')))124 ],125 features={126 'speedups': Feature("optional C speed-enhancements",127 standard=True,11 unmodified lines