File: __init__.py

package info (click to toggle)
aiohttp-jinja2 1.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 264 kB
  • sloc: python: 884; makefile: 182
file content (268 lines) | stat: -rw-r--r-- 7,914 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import functools
from typing import (
    Any,
    Awaitable,
    Callable,
    Dict,
    Final,
    Mapping,
    Optional,
    Protocol,
    Sequence,
    Tuple,
    TypeVar,
    Union,
    overload,
)

import jinja2
from aiohttp import web
from aiohttp.abc import AbstractView

from .helpers import GLOBAL_HELPERS, static_root_key
from .typedefs import Filters

__version__ = "1.6"

__all__ = (
    "get_env",
    "render_string",
    "render_template",
    "setup",
    "static_root_key",
    "template",
)

_TemplateReturnType = Awaitable[Union[web.StreamResponse, Mapping[str, Any]]]
_SimpleTemplateHandler = Callable[[web.Request], _TemplateReturnType]
_ContextProcessor = Callable[[web.Request], Awaitable[Dict[str, Any]]]

APP_CONTEXT_PROCESSORS_KEY: Final = web.AppKey[Sequence[_ContextProcessor]](
    "APP_CONTEXT_PROCESSORS_KEY"
)
APP_KEY: Final = web.AppKey[jinja2.Environment]("APP_KEY")
REQUEST_CONTEXT_KEY: Final = "aiohttp_jinja2_context"

_T = TypeVar("_T")
_AbstractView = TypeVar("_AbstractView", bound=AbstractView)


class _TemplateWrapper(Protocol):
    @overload
    def __call__(
        self, func: _SimpleTemplateHandler
    ) -> Callable[[web.Request], Awaitable[web.StreamResponse]]:
        ...

    @overload
    def __call__(
        self, func: Callable[[_AbstractView], _TemplateReturnType]
    ) -> Callable[[_AbstractView], Awaitable[web.StreamResponse]]:
        ...

    @overload
    def __call__(
        self, func: Callable[[_T, web.Request], _TemplateReturnType]
    ) -> Callable[[_T, web.Request], Awaitable[web.StreamResponse]]:
        ...


def setup(
    app: web.Application,
    *args: Any,
    app_key: web.AppKey[jinja2.Environment] = APP_KEY,
    context_processors: Sequence[_ContextProcessor] = (),
    filters: Optional[Filters] = None,
    default_helpers: bool = True,
    **kwargs: Any,
) -> jinja2.Environment:
    kwargs.setdefault("autoescape", True)
    env = jinja2.Environment(*args, **kwargs)
    if default_helpers:
        env.globals.update(GLOBAL_HELPERS)
    if filters is not None:
        env.filters.update(filters)
    app[app_key] = env
    if context_processors:
        app[APP_CONTEXT_PROCESSORS_KEY] = context_processors
        app.middlewares.append(context_processors_middleware)

    env.globals["app"] = app

    return env


def get_env(
    app: web.Application, *, app_key: web.AppKey[jinja2.Environment] = APP_KEY
) -> jinja2.Environment:
    try:
        return app[app_key]
    except KeyError:
        raise RuntimeError("aiohttp_jinja2.setup(...) must be called first.")


def _render_string(
    template_name: str,
    request: web.Request,
    context: Mapping[str, Any],
    app_key: web.AppKey[jinja2.Environment],
) -> Tuple[jinja2.Template, Mapping[str, Any]]:
    env = request.config_dict.get(app_key)
    if env is None:
        text = "Template engine is not initialized, call aiohttp_jinja2.setup() first"
        # in order to see meaningful exception message both: on console
        # output and rendered page we add same message to *reason* and
        # *text* arguments.
        raise web.HTTPInternalServerError(reason=text, text=text)
    try:
        template = env.get_template(template_name)
    except jinja2.TemplateNotFound as e:
        text = f"Template '{template_name}' not found"
        raise web.HTTPInternalServerError(reason=text, text=text) from e
    if not isinstance(context, Mapping):
        text = f"context should be mapping, not {type(context)}"  # type: ignore[unreachable]
        # same reason as above
        raise web.HTTPInternalServerError(reason=text, text=text)
    if request.get(REQUEST_CONTEXT_KEY):
        context = dict(request[REQUEST_CONTEXT_KEY], **context)
    return template, context


def render_string(
    template_name: str,
    request: web.Request,
    context: Mapping[str, Any],
    *,
    app_key: web.AppKey[jinja2.Environment] = APP_KEY,
) -> str:
    template, context = _render_string(template_name, request, context, app_key)
    return template.render(context)


async def render_string_async(
    template_name: str,
    request: web.Request,
    context: Mapping[str, Any],
    *,
    app_key: web.AppKey[jinja2.Environment] = APP_KEY,
) -> str:
    template, context = _render_string(template_name, request, context, app_key)
    return await template.render_async(context)


def _render_template(
    context: Optional[Mapping[str, Any]],
    encoding: str,
    status: int,
) -> Tuple[web.Response, Mapping[str, Any]]:
    response = web.Response(status=status)
    if context is None:
        context = {}
    response.content_type = "text/html"
    response.charset = encoding
    return response, context


def render_template(
    template_name: str,
    request: web.Request,
    context: Optional[Mapping[str, Any]],
    *,
    app_key: web.AppKey[jinja2.Environment] = APP_KEY,
    encoding: str = "utf-8",
    status: int = 200,
) -> web.Response:
    response, context = _render_template(context, encoding, status)
    response.text = render_string(template_name, request, context, app_key=app_key)
    return response


async def render_template_async(
    template_name: str,
    request: web.Request,
    context: Optional[Mapping[str, Any]],
    *,
    app_key: web.AppKey[jinja2.Environment] = APP_KEY,
    encoding: str = "utf-8",
    status: int = 200,
) -> web.Response:
    response, context = _render_template(context, encoding, status)
    response.text = await render_string_async(
        template_name, request, context, app_key=app_key
    )
    return response


def template(
    template_name: str,
    *,
    app_key: web.AppKey[jinja2.Environment] = APP_KEY,
    encoding: str = "utf-8",
    status: int = 200,
) -> _TemplateWrapper:
    @overload
    def wrapper(
        func: _SimpleTemplateHandler,
    ) -> Callable[[web.Request], Awaitable[web.StreamResponse]]:
        ...

    @overload
    def wrapper(
        func: Callable[[_AbstractView], _TemplateReturnType]
    ) -> Callable[[_AbstractView], Awaitable[web.StreamResponse]]:
        ...

    @overload
    def wrapper(
        func: Callable[[_T, web.Request], _TemplateReturnType]
    ) -> Callable[[_T, web.Request], Awaitable[web.StreamResponse]]:
        ...

    def wrapper(
        func: Callable[..., _TemplateReturnType]
    ) -> Callable[..., Awaitable[web.StreamResponse]]:
        # TODO(PY310): ParamSpec

        @functools.wraps(func)
        async def wrapped(*args: Any) -> web.StreamResponse:  # type: ignore[misc]
            context = await func(*args)
            if isinstance(context, web.StreamResponse):
                return context

            # Supports class based views see web.View
            if isinstance(args[0], AbstractView):
                request = args[0].request
            else:
                request = args[-1]

            env = request.config_dict.get(app_key)
            if env and env.is_async:
                response = await render_template_async(
                    template_name, request, context, app_key=app_key, encoding=encoding
                )
            else:
                response = render_template(
                    template_name, request, context, app_key=app_key, encoding=encoding
                )
            response.set_status(status)
            return response

        return wrapped

    return wrapper


@web.middleware
async def context_processors_middleware(
    request: web.Request,
    handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
    if REQUEST_CONTEXT_KEY not in request:
        request[REQUEST_CONTEXT_KEY] = {}
    for processor in request.config_dict[APP_CONTEXT_PROCESSORS_KEY]:
        request[REQUEST_CONTEXT_KEY].update(await processor(request))
    return await handler(request)


async def request_processor(request: web.Request) -> Dict[str, web.Request]:
    return {"request": request}