"""The runtime functions and state used by compiled templates.""" import functools import sys import typing as t from collections import abc from itertools import chain
from markupsafe import escape # noqa: F401 from markupsafe import Markup from markupsafe import soft_str
from .async_utils import auto_aiter from .async_utils import auto_await # noqa: F401 from .exceptions import TemplateNotFound # noqa: F401 from .exceptions import TemplateRuntimeError # noqa: F401 from .exceptions import UndefinedError from .nodes import EvalContext from .utils import _PassArg from .utils import concat from .utils import internalcode from .utils import missing from .utils import Namespace # noqa: F401 from .utils import object_type_repr from .utils import pass_eval_context
V = t.TypeVar("V")
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
if t.TYPE_CHECKING: import logging import typing_extensions as te from .environment import Environment
class LoopRenderFunc(te.Protocol): def __call__(
self,
reciter: t.Iterable[V],
loop_render_func: "LoopRenderFunc",
depth: int = 0,
) -> str:
...
# these variables are exported to the template runtime
exported = [ "LoopContext", "TemplateReference", "Macro", "Markup", "TemplateRuntimeError", "missing", "escape", "markup_join", "str_join", "identity", "TemplateNotFound", "Namespace", "Undefined", "internalcode",
]
async_exported = [ "AsyncLoopContext", "auto_aiter", "auto_await",
]
def identity(x: V) -> V: """Returns its argument. Useful for certain things in the
environment. """ return x
def markup_join(seq: t.Iterable[t.Any]) -> str: """Concatenation that escapes if necessary and converts to string."""
buf = []
iterator = map(soft_str, seq) for arg in iterator:
buf.append(arg) if hasattr(arg, "__html__"): return Markup("").join(chain(buf, iterator)) return concat(buf)
def str_join(seq: t.Iterable[t.Any]) -> str: """Simple args to string conversion and concatenation.""" return concat(map(str, seq))
def new_context(
environment: "Environment",
template_name: t.Optional[str],
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
vars: t.Optional[t.Dict[str, t.Any]] = None,
shared: bool = False,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
locals: t.Optional[t.Mapping[str, t.Any]] = None,
) -> "Context": """Internal helper for context creation.""" if vars isNone:
vars = {} if shared:
parent = vars else:
parent = dict(globals or (), **vars) if locals: # if the parent is shared a copy should be created because # we don't want to modify the dict passed if shared:
parent = dict(parent) for key, value in locals.items(): if value isnot missing:
parent[key] = value return environment.context_class(
environment, parent, template_name, blocks, globals=globals
)
class TemplateReference: """The `self` in templates."""
@abc.Mapping.register class Context: """The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters andglobal functions marked as
:func:`pass_context` get the active context passed as first argument and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables. """
# create the initial mapping of blocks. Whenever template inheritance # takes place the runtime will update this mapping with the new blocks # from the template.
self.blocks = {k: [v] for k, v in blocks.items()}
def super(
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
) -> t.Union["BlockReference", "Undefined"]: """Render a parent block.""" try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index] except LookupError: return self.environment.undefined(
f"there is no parent block called {name!r}.", name="super"
) return BlockReference(name, self, blocks, index)
def get(self, key: str, default: t.Any = None) -> t.Any: """Look up a variable by name, or return a default if the key is not found.
:param key: The variable name to look up.
:param default: The value to returnif the key isnot found. """ try: return self[key] except KeyError: return default
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]: """Look up a variable by name, or return an :class:`Undefined`
object if the key isnot found.
If you need to add custom behavior, override
:meth:`resolve_or_missing`, not this method. The various lookup
functions use that method, not this one.
:param key: The variable name to look up. """
rv = self.resolve_or_missing(key)
if rv is missing: return self.environment.undefined(name=key)
return rv
def resolve_or_missing(self, key: str) -> t.Any: """Look up a variable by name, or return a ``missing`` sentinel if the key isnot found.
Override this method to add custom lookup behavior.
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
method. Don't call this method directly.
:param key: The variable name to look up. """ if key in self.vars: return self.vars[key]
if key in self.parent: return self.parent[key]
return missing
def get_exported(self) -> t.Dict[str, t.Any]: """Get a new dict with the exported variables.""" return {k: self.vars[k] for k in self.exported_vars}
def get_all(self) -> t.Dict[str, t.Any]: """Return the complete context as dict including the exported
variables. For optimizations reasons this might notreturn an
actual copy so be careful with using it. """ ifnot self.vars: return self.parent ifnot self.parent: return self.vars return dict(self.parent, **self.vars)
@internalcode def call(
__self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902
) -> t.Union[t.Any, "Undefined"]: """Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable has :func:`pass_context` or
:func:`pass_environment`. """ if __debug__:
__traceback_hide__ = True# noqa
# Allow callable classes to take a context if (
hasattr(__obj, "__call__") # noqa: B004 and _PassArg.from_obj(__obj.__call__) isnotNone# type: ignore
):
__obj = __obj.__call__ # type: ignore
pass_arg = _PassArg.from_obj(__obj)
if pass_arg is _PassArg.context: # the active context should have access to variables set in # loops and blocks without mutating the context itself if kwargs.get("_loop_vars"):
__self = __self.derived(kwargs["_loop_vars"]) if kwargs.get("_block_vars"):
__self = __self.derived(kwargs["_block_vars"])
args = (__self,) + args elif pass_arg is _PassArg.eval_context:
args = (__self.eval_ctx,) + args elif pass_arg is _PassArg.environment:
args = (__self.environment,) + args
try: return __obj(*args, **kwargs) except StopIteration: return __self.environment.undefined( "value was undefined because a callable raised a" " StopIteration exception"
)
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context": """Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent. """
context = new_context(
self.environment, self.name, {}, self.get_all(), True, None, locals
)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.items()) return context
def __contains__(self, name: str) -> bool: return name in self.vars or name in self.parent
def __getitem__(self, key: str) -> t.Any: """Look up a variable by name with ``[]`` syntax, or raise a
``KeyError`` if the key isnot found. """
item = self.resolve_or_missing(key)
if item is missing: raise KeyError(key)
return item
def __repr__(self) -> str: return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
class BlockReference: """One block on a template reference."""
def __init__(
self,
iterable: t.Iterable[V],
undefined: t.Type["Undefined"],
recurse: t.Optional["LoopRenderFunc"] = None,
depth0: int = 0,
) -> None: """
:param iterable: Iterable to wrap.
:param undefined: :class:`Undefined` class to use for next and
previous items.
:param recurse: The function to render the loop body when the
loop is marked recursive.
:param depth0: Incremented when looping recursively. """
self._iterable = iterable
self._iterator = self._to_iterator(iterable)
self._undefined = undefined
self._recurse = recurse #: How many levels deep a recursive loop currently is, starting at 0.
self.depth0 = depth0
@property def length(self) -> int: """Length of the iterable.
If the iterable is a generator or otherwise does not have a
size, it is eagerly evaluated to get a size. """ if self._length isnotNone: return self._length
@property def first(self) -> bool: """Whether this is the first iteration of the loop.""" return self.index0 == 0
def _peek_next(self) -> t.Any: """Return the next element in the iterable, or :data:`missing` if the iterable is exhausted. Only peeks one item ahead, caching
the result in :attr:`_last` for use in subsequent checks. The
cache is reset when :meth:`__next__` is called. """ if self._after isnot missing: return self._after
@property def last(self) -> bool: """Whether this is the last iteration of the loop.
Causes the iterable to advance early. See
:func:`itertools.groupby` for issues this can cause.
The :func:`groupby` filter avoids that issue. """ return self._peek_next() is missing
@property def previtem(self) -> t.Union[t.Any, "Undefined"]: """The item in the previous iteration. Undefined during the
first iteration. """ if self.first: return self._undefined("there is no previous item")
return self._before
@property def nextitem(self) -> t.Union[t.Any, "Undefined"]: """The item in the next iteration. Undefined during the last
iteration.
Causes the iterable to advance early. See
:func:`itertools.groupby` for issues this can cause.
The :func:`jinja-filters.groupby` filter avoids that issue. """
rv = self._peek_next()
if rv is missing: return self._undefined("there is no next item")
return rv
def cycle(self, *args: V) -> V: """Return a value from the given args, cycling through based on
the current :attr:`index0`.
:param args: One or more values to cycle through. """ ifnot args: raise TypeError("no items for cycling given")
return args[self.index0 % len(args)]
def changed(self, *value: t.Any) -> bool: """Return ``True`` if previously called with a different value
(including when called for the first time).
:param value: One or more values to compare to the last call. """ if self._last_changed_value != value:
self._last_changed_value = value returnTrue
@internalcode def __call__(self, iterable: t.Iterable[V]) -> str: """When iterating over nested data, render the body of the loop
recursively with the given inner iterable data.
The loop must have the ``recursive`` marker for this to work. """ if self._recurse isNone: raise TypeError( "The loop must have the 'recursive' marker to be called recursively."
)
if default_autoescape isNone: if callable(environment.autoescape):
default_autoescape = environment.autoescape(None) else:
default_autoescape = environment.autoescape
self._default_autoescape = default_autoescape
@internalcode
@pass_eval_context def __call__(self, *args: t.Any, **kwargs: t.Any) -> str: # This requires a bit of explanation, In the past we used to # decide largely based on compile-time information if a macro is # safe or unsafe. While there was a volatile mode it was largely # unused for deciding on escaping. This turns out to be # problematic for macros because whether a macro is safe depends not # on the escape mode when it was defined, but rather when it was used. # # Because however we export macros from the module system and # there are historic callers that do not pass an eval context (and # will continue to not pass one), we need to perform an instance # check here. # # This is considered safe because an eval context is not a valid # argument to callables otherwise anyway. Worst case here is # that if no eval context is passed we fall back to the compile # time autoescape flag. if args and isinstance(args[0], EvalContext):
autoescape = args[0].autoescape
args = args[1:] else:
autoescape = self._default_autoescape
# try to consume the positional arguments
arguments = list(args[: self._argument_count])
off = len(arguments)
# For information why this is necessary refer to the handling # of caller in the `macro_body` handler in the compiler.
found_caller = False
# if the number of arguments consumed is not the number of # arguments expected we start filling in keyword arguments # and defaults. if off != self._argument_count: for name in self.arguments[len(arguments) :]: try:
value = kwargs.pop(name) except KeyError:
value = missing if name == "caller":
found_caller = True
arguments.append(value) else:
found_caller = self.explicit_caller
# it's important that the order of these arguments does not change # if not also changed in the compiler's `function_scoping` method. # the order is caller, keyword arguments, positional arguments! if self.caller andnot found_caller:
caller = kwargs.pop("caller", None) if caller isNone:
caller = self._environment.undefined("No caller defined", name="caller")
arguments.append(caller)
if self.catch_kwargs:
arguments.append(kwargs) elif kwargs: if"caller"in kwargs: raise TypeError(
f"macro {self.name!r} was invoked with two values for the special" " caller argument. This is most likely a bug."
) raise TypeError(
f"macro {self.name!r} takes no keyword argument {next(iter(kwargs))!r}"
) if self.catch_varargs:
arguments.append(args[self._argument_count :]) elif len(args) > self._argument_count: raise TypeError(
f"macro {self.name!r} takes not more than"
f" {len(self.arguments)} argument(s)"
)
class Undefined: """The default undefined type. This undefined type can be printed and
iterated over, but every other access will raise an :exc:`UndefinedError`:
@property def _undefined_message(self) -> str: """Build a message about the undefined value based on how it was
accessed. """ if self._undefined_hint: return self._undefined_hint
if self._undefined_obj is missing: return f"{self._undefined_name!r} is undefined"
ifnot isinstance(self._undefined_name, str): return (
f"{object_type_repr(self._undefined_obj)} has no"
f" element {self._undefined_name!r}"
)
return (
f"{object_type_repr(self._undefined_obj)!r} has no"
f" attribute {self._undefined_name!r}"
)
@internalcode def _fail_with_undefined_error(
self, *args: t.Any, **kwargs: t.Any
) -> "te.NoReturn": """Raise an :exc:`UndefinedError` when operations are performed
on the undefined value. """ raise self._undefined_exception(self._undefined_message)
async def __aiter__(self) -> t.AsyncIterator[t.Any]: for _ in (): yield
def __bool__(self) -> bool: returnFalse
def __repr__(self) -> str: return"Undefined"
def make_logging_undefined(
logger: t.Optional["logging.Logger"] = None, base: t.Type[Undefined] = Undefined
) -> t.Type[Undefined]: """Given a logger object this returns a new undefined class that will
log certain failures. It will log iterations and printing. If no
logger is given a default logger is created.
:param logger: the logger to use. Ifnot provided, a default logger is created.
:param base: the base class to add logging functionality to. This
defaults to :class:`Undefined`. """ if logger isNone: import logging
class ChainableUndefined(Undefined): """An undefined that is chainable, where both ``__getattr__`` and
``__getitem__`` return itself rather than raising an
:exc:`UndefinedError`.
def __str__(self) -> str: if self._undefined_hint:
message = f"undefined value printed: {self._undefined_hint}"
elif self._undefined_obj is missing:
message = self._undefined_name # type: ignore
else:
message = (
f"no such element: {object_type_repr(self._undefined_obj)}"
f"[{self._undefined_name!r}]"
)
return f"{{{{ {message} }}}}"
class StrictUndefined(Undefined): """An undefined that barks on print and iteration as well as boolean
tests and all kinds of comparisons. In other words: you can do nothing with it except checking if it's defined using the `defined` test.
# Remove slots attributes, after the metaclass is applied they are # unneeded and contain wrong data for subclasses. del (
Undefined.__slots__,
ChainableUndefined.__slots__,
DebugUndefined.__slots__,
StrictUndefined.__slots__,
)
Messung V0.5
¤ Dauer der Verarbeitung: 0.14 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.