PHP 8.0.30
Preview: nativetypes.py Size: 3.88 KB
//opt/alt/python37/lib/python3.7/site-packages/jinja2/nativetypes.py

import typing as t
from ast import literal_eval
from ast import parse
from itertools import chain
from itertools import islice

from . import nodes
from .compiler import CodeGenerator
from .compiler import Frame
from .compiler import has_safe_repr
from .environment import Environment
from .environment import Template


def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]:
    """Return a native Python type from the list of compiled nodes. If
    the result is a single node, its value is returned. Otherwise, the
    nodes are concatenated as strings. If the result can be parsed with
    :func:`ast.literal_eval`, the parsed value is returned. Otherwise,
    the string is returned.

    :param values: Iterable of outputs to concatenate.
    """
    head = list(islice(values, 2))

    if not head:
        return None

    if len(head) == 1:
        raw = head[0]
        if not isinstance(raw, str):
            return raw
    else:
        raw = "".join([str(v) for v in chain(head, values)])

    try:
        return literal_eval(
            # In Python 3.10+ ast.literal_eval removes leading spaces/tabs
            # from the given string. For backwards compatibility we need to
            # parse the string ourselves without removing leading spaces/tabs.
            parse(raw, mode="eval")
        )
    except (ValueError, SyntaxError, MemoryError):
        return raw


class NativeCodeGenerator(CodeGenerator):
    """A code generator which renders Python types by not adding
    ``str()`` around output nodes.
    """

    @staticmethod
    def _default_finalize(value: t.Any) -> t.Any:
        return value

    def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:
        return repr("".join([str(v) for v in group]))

    def _output_child_to_const(
        self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
    ) -> t.Any:
        const = node.as_const(frame.eval_ctx)

        if not has_safe_repr(const):
            raise nodes.Impossible()

        if isinstance(node, nodes.TemplateData):
            return const

        return finalize.const(const)  # type: ignore

    def _output_child_pre(
        self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
    ) -> None:
        if finalize.src is not None:
            self.write(finalize.src)

    def _output_child_post(
        self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
    ) -> None:
        if finalize.src is not None:
            self.write(")")


class NativeEnvironment(Environment):
    """An environment that renders templates to native Python types."""

    code_generator_class = NativeCodeGenerator


class NativeTemplate(Template):
    environment_class = NativeEnvironment

    def render(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
        """Render the template to produce a native Python type. If the
        result is a single node, its value is returned. Otherwise, the
        nodes are concatenated as strings. If the result can be parsed
        with :func:`ast.literal_eval`, the parsed value is returned.
        Otherwise, the string is returned.
        """
        ctx = self.new_context(dict(*args, **kwargs))

        try:
            return native_concat(self.root_render_func(ctx))  # type: ignore
        except Exception:
            return self.environment.handle_exception()

    async def render_async(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
        if not self.environment.is_async:
            raise RuntimeError(
                "The environment was not created with async mode enabled."
            )

        ctx = self.new_context(dict(*args, **kwargs))

        try:
            return native_concat(
                [n async for n in self.root_render_func(ctx)]  # type: ignore
            )
        except Exception:
            return self.environment.handle_exception()


NativeEnvironment.template_class = NativeTemplate

Directory Contents

Dirs: 1 × Files: 26

Name Size Perms Modified Actions
- drwxr-xr-x 2023-12-06 03:19:44
Edit Download
1.90 KB lrw-r--r-- 2021-11-09 17:17:58
Edit Download
12.37 KB lrw-r--r-- 2021-10-04 20:41:58
Edit Download
70.52 KB lrw-r--r-- 2021-11-09 16:37:43
Edit Download
1.40 KB lrw-r--r-- 2021-04-05 17:47:37
Edit Download
8.29 KB lrw-r--r-- 2021-11-09 17:17:58
Edit Download
1.24 KB lrw-r--r-- 2021-05-10 13:52:40
Edit Download
59.55 KB lrw-r--r-- 2021-11-09 18:10:36
Edit Download
4.95 KB lrw-r--r-- 2021-05-10 13:52:40
Edit Download
31.37 KB lrw-r--r-- 2021-05-14 01:01:18
Edit Download
51.38 KB lrw-r--r-- 2021-10-04 20:41:58
Edit Download
10.47 KB lrw-r--r-- 2021-08-10 13:34:22
Edit Download
29.23 KB lrw-r--r-- 2021-10-04 20:41:58
Edit Download
22.22 KB lrw-r--r-- 2021-11-09 20:21:27
Edit Download
4.29 KB lrw-r--r-- 2021-05-10 13:52:40
Edit Download
3.88 KB lrw-r--r-- 2021-11-09 17:17:58
Edit Download
33.74 KB lrw-r--r-- 2021-11-09 17:18:01
Edit Download
1.61 KB lrw-r--r-- 2021-05-10 13:52:40
Edit Download
38.83 KB lrw-r--r-- 2021-05-14 01:01:13
Edit Download
0 B lrw-r--r-- 2021-05-10 13:52:40
Edit Download
34.23 KB lrw-r--r-- 2021-08-10 13:34:22
Edit Download
14.26 KB lrw-r--r-- 2021-05-10 13:52:40
Edit Download
5.77 KB lrw-r--r-- 2021-04-10 17:20:38
Edit Download
26.34 KB lrw-r--r-- 2021-10-04 20:41:58
Edit Download
3.49 KB lrw-r--r-- 2021-05-10 13:52:40
Edit Download
1.73 KB lrw-r--r-- 2020-02-17 17:14:56
Edit Download
2.15 KB lrw-r--r-- 2021-11-09 20:25:25
Edit Download

If ZipArchive is unavailable, a .tar will be created (no compression).