Skip to content
Myr

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

12 files+56 added−54 removed

modified:docs/api.rst+1 added-1 removed
83 unmodified lines
84 to modify this dict. For more details see :ref:`global-namespace`.858687.. autoclass:: jinja2.Template88 :members: render, stream, generate, module88 :members: render, stream, generate, make_module, module8990 .. attribute:: globals9192 foo
244 unmodified lines
modified: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 lines
131132 /* 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);137138 /* if the object has an __html__ method that performs the escaping */139 PyObject *html = PyObject_GetAttrString(text, "__html__");140 if (html) {
14 unmodified lines
155 else156 s = escape_unicode((PyUnicodeObject*)text);157158 /* 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}163164165static PyObject *
53 unmodified lines
modified:jinja2/compiler.py+1 added-2 removed
15 unmodified lines
16from itertools import chain17from jinja2 import nodes18from jinja2.visitor import NodeVisitor, NodeTransformer19from jinja2.exceptions import TemplateAssertionError20from jinja2.runtime import concat21from jinja2.utils import Markup20from jinja2.utils import Markup, concat212223operators = {24 'eq': '==',
1218 unmodified lines
modified:jinja2/environment.py+8 added-5 removed
12 unmodified lines
13from jinja2.lexer import Lexer14from jinja2.parser import Parser15from jinja2.optimizer import optimize16from jinja2.compiler import generate17from jinja2.runtime import Undefined, Context, concat17from jinja2.runtime import Undefined, Context18from jinja2.debug import translate_exception, translate_syntax_error19from jinja2.exceptions import TemplateSyntaxError20from jinja2.utils import import_string, LRUCache, Markup, missing20from jinja2.utils import import_string, LRUCache, Markup, missing, concat212223# for direct template usage we have up to ten living environments24_spontaneous_environments = LRUCache(10)
504 unmodified lines
529 parent = dict(self.globals, **vars)530 return Context(self.environment, parent, self.name, self.blocks)531532 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))540541 @property
53 unmodified lines
595 # 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.name602603 __html__ = lambda x: Markup(concat(x.__body_stream))
70 unmodified lines
modified:jinja2/filters.py+1 added-5 removed
9 unmodified lines
10"""11import re12import math13from random import choice14try:15 from operator import itemgetter14from operator import itemgetter16except ImportError:17 itemgetter = lambda a: lambda b: b[a]18from urllib import urlencode, quote15from itertools import imap, groupby16from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode17from jinja2.runtime import Undefined18from jinja2.exceptions import FilterArgumentError
651 unmodified lines
modified:jinja2/nodes.py+1 added-1 removed
11 unmodified lines
12 :copyright: 2008 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14"""15import operator16from copy import copy17from types import FunctionType18from itertools import chain, izip19from collections import deque19from copy import copy20from jinja2.utils import Markup212223_binop_to_func = {
606 unmodified lines
modified:jinja2/optimizer.py+2 added-1 removed
16 unmodified lines
17 :license: GNU GPL.18"""19from jinja2 import nodes20from jinja2.visitor import NodeVisitor, NodeTransformer21from jinja2.runtime import LoopContext, concat21from jinja2.runtime import LoopContext22from jinja2.utils import concat232425def optimize(node, environment, context_hint=None):26 """The context hint can be used to perform an static optimization
155 unmodified lines
modified:jinja2/runtime.py+1 added-22 removed
9 unmodified lines
10"""11import sys12from types import FunctionType13from itertools import chain, imap14from jinja2.utils import Markup, partial, soft_unicode, escape, missing14from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat15from jinja2.exceptions import UndefinedError, TemplateRuntimeError161718# these variables are exported to the template runtime
1 unmodified line
20 'TemplateRuntimeError', 'missing', 'concat', 'escape',21 'markup_join', 'unicode_join']222324# 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.27try:28 def _test_gen_bug():29 raise TypeError(_test_gen_bug)30 yield None31 u''.join(_test_gen_bug())32except 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, _error434424def markup_join(*args):25 """Concatenation that escapes if necessary and converts to unicode."""26 buf = []27 iterator = imap(soft_unicode, args)
359 unmodified lines
modified:jinja2/sandbox.py+5 added-3 removed
21 unmodified lines
222324def 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 rng
29 unmodified lines
6162 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))7071 def subscribe(self, obj, argument):72 """Subscribe an object from sandboxed code."""73 is_unsafe = False
26 unmodified lines
modified:jinja2/utils.py+23 added
31 unmodified lines
32# special singleton representing missing values for the runtime33missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()343536# 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.39try:40 def _test_gen_bug():41 raise TypeError(_test_gen_bug)42 yield None43 u''.join(_test_gen_bug())44except 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, _error575859def 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 lines
modified:tests/test_imports.py+3 added-1 removed
11 unmodified lines
12test_env = Environment(loader=DictLoader(dict(13 module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',14 header='[{{ foo }}|{{ 23 }}]'15)))16test_env.globals['bar'] = '23'16test_env.globals['bar'] = 23171819def test_context_imports():20 t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')
22 unmodified lines
43def 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 lines
119 '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