| 1 |
import functools |
| 2 |
from typing import ( |
| 3 |
Any, |
| 4 |
Awaitable, |
| 5 |
Callable, |
| 6 |
Dict, |
| 7 |
Final, |
| 8 |
Mapping, |
| 9 |
Optional, |
| 10 |
Protocol, |
| 11 |
Sequence, |
| 12 |
Tuple, |
| 13 |
TypeVar, |
| 14 |
Union, |
| 15 |
overload, |
| 16 |
) |
| 17 |
|
| 18 |
import jinja2 |
| 19 |
from aiohttp import web |
| 20 |
from aiohttp.abc import AbstractView |
| 21 |
|
| 22 |
from .helpers import GLOBAL_HELPERS, static_root_key |
| 23 |
from .typedefs import Filters |
| 24 |
|
| 25 |
__version__ = "1.6" |
| 26 |
|
| 27 |
__all__ = ( |
| 28 |
"get_env", |
| 29 |
"render_string", |
| 30 |
"render_template", |
| 31 |
"setup", |
| 32 |
"static_root_key", |
| 33 |
"template", |
| 34 |
) |
| 35 |
|
| 36 |
_TemplateReturnType = Awaitable[Union[web.StreamResponse, Mapping[str, Any]]] |
| 37 |
_SimpleTemplateHandler = Callable[[web.Request], _TemplateReturnType] |
| 38 |
_ContextProcessor = Callable[[web.Request], Awaitable[Dict[str, Any]]] |
| 39 |
|
| 40 |
APP_CONTEXT_PROCESSORS_KEY: Final = web.AppKey[Sequence[_ContextProcessor]]( |
| 41 |
"APP_CONTEXT_PROCESSORS_KEY" |
| 42 |
) |
| 43 |
APP_KEY: Final = web.AppKey[jinja2.Environment]("APP_KEY") |
| 44 |
REQUEST_CONTEXT_KEY: Final = "aiohttp_jinja2_context" |
| 45 |
|
| 46 |
_T = TypeVar("_T") |
| 47 |
_AbstractView = TypeVar("_AbstractView", bound=AbstractView) |
| 48 |
|
| 49 |
|
| 50 |
class _TemplateWrapper(Protocol): |
| 51 |
@overload |
| 52 |
def __call__( |
| 53 |
self, func: _SimpleTemplateHandler |
| 54 |
) -> Callable[[web.Request], Awaitable[web.StreamResponse]]: |
| 55 |
... |
| 56 |
|
| 57 |
@overload |
| 58 |
def __call__( |
| 59 |
self, func: Callable[[_AbstractView], _TemplateReturnType] |
| 60 |
) -> Callable[[_AbstractView], Awaitable[web.StreamResponse]]: |
| 61 |
... |
| 62 |
|
| 63 |
@overload |
| 64 |
def __call__( |
| 65 |
self, func: Callable[[_T, web.Request], _TemplateReturnType] |
| 66 |
) -> Callable[[_T, web.Request], Awaitable[web.StreamResponse]]: |
| 67 |
... |
| 68 |
|
| 69 |
|
| 70 |
def setup( |
| 71 |
app: web.Application, |
| 72 |
*args: Any, |
| 73 |
app_key: web.AppKey[jinja2.Environment] = APP_KEY, |
| 74 |
context_processors: Sequence[_ContextProcessor] = (), |
| 75 |
filters: Optional[Filters] = None, |
| 76 |
default_helpers: bool = True, |
| 77 |
**kwargs: Any, |
| 78 |
) -> jinja2.Environment: |
| 79 |
kwargs.setdefault("autoescape", True) |
| 80 |
env = jinja2.Environment(*args, **kwargs) |
| 81 |
if default_helpers: |
| 82 |
env.globals.update(GLOBAL_HELPERS) |
| 83 |
if filters is not None: |
| 84 |
env.filters.update(filters) |
| 85 |
app[app_key] = env |
| 86 |
if context_processors: |
| 87 |
app[APP_CONTEXT_PROCESSORS_KEY] = context_processors |
| 88 |
app.middlewares.append(context_processors_middleware) |
| 89 |
|
| 90 |
env.globals["app"] = app |
| 91 |
|
| 92 |
return env |
| 93 |
|
| 94 |
|
| 95 |
def get_env( |
| 96 |
app: web.Application, *, app_key: web.AppKey[jinja2.Environment] = APP_KEY |
| 97 |
) -> jinja2.Environment: |
| 98 |
try: |
| 99 |
return app[app_key] |
| 100 |
except KeyError: |
| 101 |
raise RuntimeError("aiohttp_jinja2.setup(...) must be called first.") |
| 102 |
|
| 103 |
|
| 104 |
def _render_string( |
| 105 |
template_name: str, |
| 106 |
request: web.Request, |
| 107 |
context: Mapping[str, Any], |
| 108 |
app_key: web.AppKey[jinja2.Environment], |
| 109 |
) -> Tuple[jinja2.Template, Mapping[str, Any]]: |
| 110 |
env = request.config_dict.get(app_key) |
| 111 |
if env is None: |
| 112 |
text = "Template engine is not initialized, call aiohttp_jinja2.setup() first" |
| 113 |
# in order to see meaningful exception message both: on console |
| 114 |
# output and rendered page we add same message to *reason* and |
| 115 |
# *text* arguments. |
| 116 |
raise web.HTTPInternalServerError(reason=text, text=text) |
| 117 |
try: |
| 118 |
template = env.get_template(template_name) |
| 119 |
except jinja2.TemplateNotFound as e: |
| 120 |
text = f"Template '{template_name}' not found" |
| 121 |
raise web.HTTPInternalServerError(reason=text, text=text) from e |
| 122 |
if not isinstance(context, Mapping): |
| 123 |
text = f"context should be mapping, not {type(context)}" # type: ignore[unreachable] |
| 124 |
# same reason as above |
| 125 |
raise web.HTTPInternalServerError(reason=text, text=text) |
| 126 |
if request.get(REQUEST_CONTEXT_KEY): |
| 127 |
context = dict(request[REQUEST_CONTEXT_KEY], **context) |
| 128 |
return template, context |
| 129 |
|
| 130 |
|
| 131 |
def render_string( |
| 132 |
template_name: str, |
| 133 |
request: web.Request, |
| 134 |
context: Mapping[str, Any], |
| 135 |
*, |
| 136 |
app_key: web.AppKey[jinja2.Environment] = APP_KEY, |
| 137 |
) -> str: |
| 138 |
template, context = _render_string(template_name, request, context, app_key) |
| 139 |
return template.render(context) |
| 140 |
|
| 141 |
|
| 142 |
async def render_string_async( |
| 143 |
template_name: str, |
| 144 |
request: web.Request, |
| 145 |
context: Mapping[str, Any], |
| 146 |
*, |
| 147 |
app_key: web.AppKey[jinja2.Environment] = APP_KEY, |
| 148 |
) -> str: |
| 149 |
template, context = _render_string(template_name, request, context, app_key) |
| 150 |
return await template.render_async(context) |
| 151 |
|
| 152 |
|
| 153 |
def _render_template( |
| 154 |
context: Optional[Mapping[str, Any]], |
| 155 |
encoding: str, |
| 156 |
status: int, |
| 157 |
) -> Tuple[web.Response, Mapping[str, Any]]: |
| 158 |
response = web.Response(status=status) |
| 159 |
if context is None: |
| 160 |
context = {} |
| 161 |
response.content_type = "text/html" |
| 162 |
response.charset = encoding |
| 163 |
return response, context |
| 164 |
|
| 165 |
|
| 166 |
def render_template( |
| 167 |
template_name: str, |
| 168 |
request: web.Request, |
| 169 |
context: Optional[Mapping[str, Any]], |
| 170 |
*, |
| 171 |
app_key: web.AppKey[jinja2.Environment] = APP_KEY, |
| 172 |
encoding: str = "utf-8", |
| 173 |
status: int = 200, |
| 174 |
) -> web.Response: |
| 175 |
response, context = _render_template(context, encoding, status) |
| 176 |
response.text = render_string(template_name, request, context, app_key=app_key) |
| 177 |
return response |
| 178 |
|
| 179 |
|
| 180 |
async def render_template_async( |
| 181 |
template_name: str, |
| 182 |
request: web.Request, |
| 183 |
context: Optional[Mapping[str, Any]], |
| 184 |
*, |
| 185 |
app_key: web.AppKey[jinja2.Environment] = APP_KEY, |
| 186 |
encoding: str = "utf-8", |
| 187 |
status: int = 200, |
| 188 |
) -> web.Response: |
| 189 |
response, context = _render_template(context, encoding, status) |
| 190 |
response.text = await render_string_async( |
| 191 |
template_name, request, context, app_key=app_key |
| 192 |
) |
| 193 |
return response |
| 194 |
|
| 195 |
|
| 196 |
def template( |
| 197 |
template_name: str, |
| 198 |
*, |
| 199 |
app_key: web.AppKey[jinja2.Environment] = APP_KEY, |
| 200 |
encoding: str = "utf-8", |
| 201 |
status: int = 200, |
| 202 |
) -> _TemplateWrapper: |
| 203 |
@overload |
| 204 |
def wrapper( |
| 205 |
func: _SimpleTemplateHandler, |
| 206 |
) -> Callable[[web.Request], Awaitable[web.StreamResponse]]: |
| 207 |
... |
| 208 |
|
| 209 |
@overload |
| 210 |
def wrapper( |
| 211 |
func: Callable[[_AbstractView], _TemplateReturnType] |
| 212 |
) -> Callable[[_AbstractView], Awaitable[web.StreamResponse]]: |
| 213 |
... |
| 214 |
|
| 215 |
@overload |
| 216 |
def wrapper( |
| 217 |
func: Callable[[_T, web.Request], _TemplateReturnType] |
| 218 |
) -> Callable[[_T, web.Request], Awaitable[web.StreamResponse]]: |
| 219 |
... |
| 220 |
|
| 221 |
def wrapper( |
| 222 |
func: Callable[..., _TemplateReturnType] |
| 223 |
) -> Callable[..., Awaitable[web.StreamResponse]]: |
| 224 |
# TODO(PY310): ParamSpec |
| 225 |
|
| 226 |
@functools.wraps(func) |
| 227 |
async def wrapped(*args: Any) -> web.StreamResponse: # type: ignore[misc] |
| 228 |
context = await func(*args) |
| 229 |
if isinstance(context, web.StreamResponse): |
| 230 |
return context |
| 231 |
|
| 232 |
# Supports class based views see web.View |
| 233 |
if isinstance(args[0], AbstractView): |
| 234 |
request = args[0].request |
| 235 |
else: |
| 236 |
request = args[-1] |
| 237 |
|
| 238 |
env = request.config_dict.get(app_key) |
| 239 |
if env and env.is_async: |
| 240 |
response = await render_template_async( |
| 241 |
template_name, request, context, app_key=app_key, encoding=encoding |
| 242 |
) |
| 243 |
else: |
| 244 |
response = render_template( |
| 245 |
template_name, request, context, app_key=app_key, encoding=encoding |
| 246 |
) |
| 247 |
response.set_status(status) |
| 248 |
return response |
| 249 |
|
| 250 |
return wrapped |
| 251 |
|
| 252 |
return wrapper |
| 253 |
|
| 254 |
|
| 255 |
@web.middleware |
| 256 |
async def context_processors_middleware( |
| 257 |
request: web.Request, |
| 258 |
handler: Callable[[web.Request], Awaitable[web.StreamResponse]], |
| 259 |
) -> web.StreamResponse: |
| 260 |
if REQUEST_CONTEXT_KEY not in request: |
| 261 |
request[REQUEST_CONTEXT_KEY] = {} |
| 262 |
for processor in request.config_dict[APP_CONTEXT_PROCESSORS_KEY]: |
| 263 |
request[REQUEST_CONTEXT_KEY].update(await processor(request)) |
| 264 |
return await handler(request) |
| 265 |
|
| 266 |
|
| 267 |
async def request_processor(request: web.Request) -> Dict[str, web.Request]: |
| 268 |
return {"request": request} |