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