Skip to content
Myr

runtime.py

This file

Path

jinja2/runtime.py

517 lines · 16.9 KiB · Python

Last changed by

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    jinja2.runtime4    ~~~~~~~~~~~~~~56    Runtime helpers.78    :copyright: (c) 2009 by the Jinja Team.9    :license: BSD.10"""11import sys12from itertools import chain, imap13from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \14     concat, MethodType, FunctionType, internalcode15from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16     TemplateNotFound171819# these variables are exported to the template runtime20__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',21           'TemplateRuntimeError', 'missing', 'concat', 'escape',22           'markup_join', 'unicode_join', 'TemplateNotFound']232425#: the types we support for context functions26_context_function_types = (FunctionType, MethodType)272829def markup_join(seq):30    """Concatenation that escapes if necessary and converts to unicode."""31    buf = []32    iterator = imap(soft_unicode, seq)33    for arg in iterator:34        buf.append(arg)35        if hasattr(arg, '__html__'):36            return Markup(u'').join(chain(buf, iterator))37    return concat(buf)383940def unicode_join(seq):41    """Simple args to unicode conversion and concatenation."""42    return concat(imap(unicode, seq))434445def new_context(environment, template_name, blocks, vars=None,46                shared=None, globals=None, locals=None):47    """Internal helper to for context creation."""48    if vars is None:49        vars = {}50    if shared:51        parent = vars52    else:53        parent = dict(globals or (), **vars)54    if locals:55        # if the parent is shared a copy should be created because56        # we don't want to modify the dict passed57        if shared:58            parent = dict(parent)59        for key, value in locals.iteritems():60            if key[:2] == 'l_' and value is not missing:61                parent[key[2:]] = value62    return Context(environment, parent, template_name, blocks)636465class TemplateReference(object):66    """The `self` in templates."""6768    def __init__(self, context):69        self.__context = context7071    def __getitem__(self, name):72        blocks = self.__context.blocks[name]73        wrap = self.__context.environment.autoescape and \74               Markup or (lambda x: x)75        return BlockReference(name, self.__context, blocks, 0)7677    def __repr__(self):78        return '<%s %r>' % (79            self.__class__.__name__,80            self.__context.name81        )828384class Context(object):85    """The template context holds the variables of a template.  It stores the86    values passed to the template and also the names the template exports.87    Creating instances is neither supported nor useful as it's created88    automatically at various stages of the template evaluation and should not89    be created by hand.9091    The context is immutable.  Modifications on :attr:`parent` **must not**92    happen and modifications on :attr:`vars` are allowed from generated93    template code only.  Template filters and global functions marked as94    :func:`contextfunction`\s get the active context passed as first argument95    and are allowed to access the context read-only.9697    The template context supports read only dict operations (`get`,98    `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,99    `__getitem__`, `__contains__`).  Additionally there is a :meth:`resolve`100    method that doesn't fail with a `KeyError` but returns an101    :class:`Undefined` object for missing variables.102    """103    __slots__ = ('parent', 'vars', 'environment', 'exported_vars', 'name',104                 'blocks', '__weakref__')105106    def __init__(self, environment, parent, name, blocks):107        self.parent = parent108        self.vars = vars = {}109        self.environment = environment110        self.exported_vars = set()111        self.name = name112113        # create the initial mapping of blocks.  Whenever template inheritance114        # takes place the runtime will update this mapping with the new blocks115        # from the template.116        self.blocks = dict((k, [v]) for k, v in blocks.iteritems())117118    def super(self, name, current):119        """Render a parent block."""120        try:121            blocks = self.blocks[name]122            index = blocks.index(current) + 1123            blocks[index]124        except LookupError:125            return self.environment.undefined('there is no parent block '126                                              'called %r.' % name,127                                              name='super')128        return BlockReference(name, self, blocks, index)129130    def get(self, key, default=None):131        """Returns an item from the template context, if it doesn't exist132        `default` is returned.133        """134        try:135            return self[key]136        except KeyError:137            return default138139    def resolve(self, key):140        """Looks up a variable like `__getitem__` or `get` but returns an141        :class:`Undefined` object with the name of the name looked up.142        """143        if key in self.vars:144            return self.vars[key]145        if key in self.parent:146            return self.parent[key]147        return self.environment.undefined(name=key)148149    def get_exported(self):150        """Get a new dict with the exported variables."""151        return dict((k, self.vars[k]) for k in self.exported_vars)152153    def get_all(self):154        """Return a copy of the complete context as dict including the155        exported variables.156        """157        return dict(self.parent, **self.vars)158159    @internalcode160    def call(__self, __obj, *args, **kwargs):161        """Call the callable with the arguments and keyword arguments162        provided but inject the active context or environment as first163        argument if the callable is a :func:`contextfunction` or164        :func:`environmentfunction`.165        """166        if __debug__:167            __traceback_hide__ = True168        if isinstance(__obj, _context_function_types):169            if getattr(__obj, 'contextfunction', 0):170                args = (__self,) + args171            elif getattr(__obj, 'environmentfunction', 0):172                args = (__self.environment,) + args173        return __obj(*args, **kwargs)174175    def derived(self, locals=None):176        """Internal helper function to create a derived context."""177        context = new_context(self.environment, self.name, {},178                              self.parent, True, None, locals)179        context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())180        return context181182    def _all(meth):183        proxy = lambda self: getattr(self.get_all(), meth)()184        proxy.__doc__ = getattr(dict, meth).__doc__185        proxy.__name__ = meth186        return proxy187188    keys = _all('keys')189    values = _all('values')190    items = _all('items')191    iterkeys = _all('iterkeys')192    itervalues = _all('itervalues')193    iteritems = _all('iteritems')194    del _all195196    def __contains__(self, name):197        return name in self.vars or name in self.parent198199    def __getitem__(self, key):200        """Lookup a variable or raise `KeyError` if the variable is201        undefined.202        """203        item = self.resolve(key)204        if isinstance(item, Undefined):205            raise KeyError(key)206        return item207208    def __repr__(self):209        return '<%s %s of %r>' % (210            self.__class__.__name__,211            repr(self.get_all()),212            self.name213        )214215216# register the context as mapping if possible217try:218    from collections import Mapping219    Mapping.register(Context)220except ImportError:221    pass222223224class BlockReference(object):225    """One block on a template reference."""226227    def __init__(self, name, context, stack, depth):228        self.name = name229        self._context = context230        self._stack = stack231        self._depth = depth232233    @property234    def super(self):235        """Super the block."""236        if self._depth + 1 >= len(self._stack):237            return self._context.environment. \238                undefined('there is no parent block called %r.' %239                          self.name, name='super')240        return BlockReference(self.name, self._context, self._stack,241                              self._depth + 1)242243    @internalcode244    def __call__(self):245        rv = concat(self._stack[self._depth](self._context))246        if self._context.environment.autoescape:247            rv = Markup(rv)248        return rv249250251class LoopContext(object):252    """A loop context for dynamic iteration."""253254    def __init__(self, iterable, recurse=None):255        self._iterator = iter(iterable)256        self._recurse = recurse257        self.index0 = -1258259        # try to get the length of the iterable early.  This must be done260        # here because there are some broken iterators around where there261        # __len__ is the number of iterations left (i'm looking at your262        # listreverseiterator!).263        try:264            self._length = len(iterable)265        except (TypeError, AttributeError):266            self._length = None267268    def cycle(self, *args):269        """Cycles among the arguments with the current loop index."""270        if not args:271            raise TypeError('no items for cycling given')272        return args[self.index0 % len(args)]273274    first = property(lambda x: x.index0 == 0)275    last = property(lambda x: x.index0 + 1 == x.length)276    index = property(lambda x: x.index0 + 1)277    revindex = property(lambda x: x.length - x.index0)278    revindex0 = property(lambda x: x.length - x.index)279280    def __len__(self):281        return self.length282283    def __iter__(self):284        return LoopContextIterator(self)285286    @internalcode287    def loop(self, iterable):288        if self._recurse is None:289            raise TypeError('Tried to call non recursive loop.  Maybe you '290                            "forgot the 'recursive' modifier.")291        return self._recurse(iterable, self._recurse)292293    # a nifty trick to enhance the error message if someone tried to call294    # the the loop without or with too many arguments.295    __call__ = loop; del loop296297    @property298    def length(self):299        if self._length is None:300            # if was not possible to get the length of the iterator when301            # the loop context was created (ie: iterating over a generator)302            # we have to convert the iterable into a sequence and use the303            # length of that.304            iterable = tuple(self._iterator)305            self._iterator = iter(iterable)306            self._length = len(iterable) + self.index0 + 1307        return self._length308309    def __repr__(self):310        return '<%s %r/%r>' % (311            self.__class__.__name__,312            self.index,313            self.length314        )315316317class LoopContextIterator(object):318    """The iterator for a loop context."""319    __slots__ = ('context',)320321    def __init__(self, context):322        self.context = context323324    def __iter__(self):325        return self326327    def next(self):328        ctx = self.context329        ctx.index0 += 1330        return ctx._iterator.next(), ctx331332333class Macro(object):334    """Wraps a macro."""335336    def __init__(self, environment, func, name, arguments, defaults,337                 catch_kwargs, catch_varargs, caller):338        self._environment = environment339        self._func = func340        self._argument_count = len(arguments)341        self.name = name342        self.arguments = arguments343        self.defaults = defaults344        self.catch_kwargs = catch_kwargs345        self.catch_varargs = catch_varargs346        self.caller = caller347348    @internalcode349    def __call__(self, *args, **kwargs):350        arguments = []351        for idx, name in enumerate(self.arguments):352            try:353                value = args[idx]354            except:355                try:356                    value = kwargs.pop(name)357                except:358                    try:359                        value = self.defaults[idx - self._argument_count]360                    except:361                        value = self._environment.undefined(362                            'parameter %r was not provided' % name, name=name)363            arguments.append(value)364365        # it's important that the order of these arguments does not change366        # if not also changed in the compiler's `function_scoping` method.367        # the order is caller, keyword arguments, positional arguments!368        if self.caller:369            caller = kwargs.pop('caller', None)370            if caller is None:371                caller = self._environment.undefined('No caller defined',372                                                     name='caller')373            arguments.append(caller)374        if self.catch_kwargs:375            arguments.append(kwargs)376        elif kwargs:377            raise TypeError('macro %r takes no keyword argument %r' %378                            (self.name, iter(kwargs).next()))379        if self.catch_varargs:380            arguments.append(args[self._argument_count:])381        elif len(args) > self._argument_count:382            raise TypeError('macro %r takes not more than %d argument(s)' %383                            (self.name, len(self.arguments)))384        return self._func(*arguments)385386    def __repr__(self):387        return '<%s %s>' % (388            self.__class__.__name__,389            self.name is None and 'anonymous' or repr(self.name)390        )391392393class Undefined(object):394    """The default undefined type.  This undefined type can be printed and395    iterated over, but every other access will raise an :exc:`UndefinedError`:396397    >>> foo = Undefined(name='foo')398    >>> str(foo)399    ''400    >>> not foo401    True402    >>> foo + 42403    Traceback (most recent call last):404      ...405    UndefinedError: 'foo' is undefined406    """407    __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',408                 '_undefined_exception')409410    def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):411        self._undefined_hint = hint412        self._undefined_obj = obj413        self._undefined_name = name414        self._undefined_exception = exc415416    @internalcode417    def _fail_with_undefined_error(self, *args, **kwargs):418        """Regular callback function for undefined objects that raises an419        `UndefinedError` on call.420        """421        if self._undefined_hint is None:422            if self._undefined_obj is None:423                hint = '%r is undefined' % self._undefined_name424            elif not isinstance(self._undefined_name, basestring):425                hint = '%r object has no element %r' % (426                    self._undefined_obj.__class__.__name__,427                    self._undefined_name428                )429            else:430                hint = '%r object has no attribute %r' % (431                    self._undefined_obj.__class__.__name__,432                    self._undefined_name433                )434        else:435            hint = self._undefined_hint436        raise self._undefined_exception(hint)437438    __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \439    __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \440    __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \441    __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \442    __int__ = __float__ = __complex__ = __pow__ = __rpow__ = \443        _fail_with_undefined_error444445    def __str__(self):446        return unicode(self).encode('utf-8')447448    def __unicode__(self):449        return u''450451    def __len__(self):452        return 0453454    def __iter__(self):455        if 0:456            yield None457458    def __nonzero__(self):459        return False460461    def __repr__(self):462        return 'Undefined'463464465class DebugUndefined(Undefined):466    """An undefined that returns the debug info when printed.467468    >>> foo = DebugUndefined(name='foo')469    >>> str(foo)470    '{{ foo }}'471    >>> not foo472    True473    >>> foo + 42474    Traceback (most recent call last):475      ...476    UndefinedError: 'foo' is undefined477    """478    __slots__ = ()479480    def __unicode__(self):481        if self._undefined_hint is None:482            if self._undefined_obj is None:483                return u'{{ %s }}' % self._undefined_name484            return '{{ no such element: %s[%r] }}' % (485                self._undefined_obj.__class__.__name__,486                self._undefined_name487            )488        return u'{{ undefined value printed: %s }}' % self._undefined_hint489490491class StrictUndefined(Undefined):492    """An undefined that barks on print and iteration as well as boolean493    tests and all kinds of comparisons.  In other words: you can do nothing494    with it except checking if it's defined using the `defined` test.495496    >>> foo = StrictUndefined(name='foo')497    >>> str(foo)498    Traceback (most recent call last):499      ...500    UndefinedError: 'foo' is undefined501    >>> not foo502    Traceback (most recent call last):503      ...504    UndefinedError: 'foo' is undefined505    >>> foo + 42506    Traceback (most recent call last):507      ...508    UndefinedError: 'foo' is undefined509    """510    __slots__ = ()511    __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \512        Undefined._fail_with_undefined_error513514515# remove remaining slots attributes, after the metaclass did the magic they516# are unneeded and irritating as they contain wrong data for the subclasses.517del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__