Coverage for fastblocks / adapters / templates / jinja2.py: 60%
620 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Jinja2 Templates Adapter for FastBlocks.
3Provides asynchronous Jinja2 template rendering with advanced features including:
4- Multi-layer loader system (Redis cache, cloud storage, filesystem)
5- Bidirectional integration with HTMY components via dedicated HTMY adapter
6- Fragment and partial template support
7- Bytecode caching with Redis backend
8- Template synchronization across cache/storage/filesystem layers
9- Custom delimiters ([[/]] instead of {{/}})
10- Extensive template debugging and error handling
12Requirements:
13- jinja2-async-environment>=0.14.3
14- starlette-async-jinja>=1.12.4
15- jinja2>=3.1.6
16- redis>=3.5.3 (for caching)
18Usage:
19```python
20# ACB imports removed - using Oneiric equivalents
21# templates = depends.resolve("fastblocks", "templates")
22# Templates = import_adapter("templates")
23# response = await templates.render_template(
24# request, "index.html", {"title": "FastBlocks"}
25)
26```
28Author: lesleslie <les@wedgwoodwebworks.com>
29Created: 2025-01-12
30"""
32import asyncio
33import re
35# Import Oneiric registration helper
36import sys
37import typing as t
38from ast import literal_eval
39from contextlib import suppress
40from html.parser import HTMLParser
41from importlib import import_module
42from importlib.util import find_spec
43from inspect import isclass
44from pathlib import Path
45from uuid import UUID
47from oneiric.core.config import OneiricSettings
48from oneiric.core.resolution import Resolver
50# Add parent directory to path for helper import
51sys.path.insert(0, str(Path(__file__).parent.parent))
52from oneiric_helper import register_candidate
54# Import event tracking decorator (with fallback if unavailable)
55try:
56 from ._events_wrapper import track_template_render
57except ImportError:
58 # Fallback no-op decorator if events integration unavailable
59 def track_template_render(func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
60 return func
63# Custom implementations for ACB compatibility
64def get_adapter(adapter_name: str) -> t.Any:
65 """Custom implementation for Oneiric compatibility."""
66 # This will be implemented using Oneiric's adapter system
67 return None
70class AdapterStatus:
71 """Custom AdapterStatus for Oneiric compatibility."""
73 STABLE = "STABLE"
74 BETA = "BETA"
75 ALPHA = "ALPHA"
76 EXPERIMENTAL = "EXPERIMENTAL"
79def debug(msg: str) -> None:
80 """Custom debug function for Oneiric compatibility."""
81 print(f"[DEBUG] {msg}")
84# Oneiric resolver for dependency injection
85depends = Resolver()
88from anyio import Path as AsyncPath
89from jinja2 import TemplateNotFound
90from jinja2.ext import Extension, i18n, loopcontrols
91from jinja2.ext import debug as jinja_debug
92from jinja2_async_environment import AsyncRedisBytecodeCache
93from jinja2_async_environment.loaders import AsyncBaseLoader, SourceType
94from starlette_async_jinja import AsyncJinja2Templates
95from fastblocks.actions.sync.strategies import SyncDirection, SyncStrategy
96from fastblocks.actions.sync.templates import sync_templates
98from ._base import TemplatesBase, TemplatesBaseSettings
100Cache, Storage, Models = None, None, None
102_TEMPLATE_REPLACEMENTS = [
103 (b"{{", b"[["),
104 (b"}}", b"]]"),
105 (b"{%", b"[%"),
106 (b"%}", b"%]"),
107]
108_HTTP_TO_HTTPS = (b"http://", b"https://")
110_ATTR_PATTERN_CACHE: dict[str, re.Pattern[str]] = {}
113def _get_attr_pattern(attr: str) -> re.Pattern[str]:
114 if attr not in _ATTR_PATTERN_CACHE:
115 escaped_attr = re.escape(f"{attr}=")
116 _ATTR_PATTERN_CACHE[attr] = re.compile(
117 escaped_attr
118 ) # REGEX OK: Template attribute pattern compilation for Jinja2
119 return _ATTR_PATTERN_CACHE[attr]
122def _try_resolve_sync(key: str) -> t.Any:
123 """Helper to try to get a Oneiric dependency synchronously.
125 This is needed for __init__ methods that can't be async.
126 """
127 try:
128 # For fallback and testing - use depends.get if it exists
129 if hasattr(depends, "get"):
130 return getattr(depends, "get")(key)
132 # Try to await the resolve call synchronously
133 import asyncio
135 result = depends.resolve("fastblocks", key)
136 loop = asyncio.new_event_loop()
137 try:
138 return loop.run_until_complete(result)
139 except Exception:
140 return None
141 except Exception:
142 return None
145def _apply_template_replacements(source: bytes, deployed: bool = False) -> bytes:
146 for old_pattern, new_pattern in _TEMPLATE_REPLACEMENTS:
147 source = source.replace(old_pattern, new_pattern)
148 if deployed:
149 source = source.replace(*_HTTP_TO_HTTPS)
151 return source
154class BaseTemplateLoader(AsyncBaseLoader):
155 config: t.Any = None
156 cache: t.Any = None
157 storage: t.Any = None
159 def __init__(
160 self,
161 searchpath: AsyncPath | t.Sequence[AsyncPath] | None = None,
162 ) -> None:
163 # Use current directory as default searchpath if none provided
164 searchpath = searchpath or [AsyncPath(".")]
165 super().__init__(searchpath)
166 if self.storage is None:
167 self.storage = _try_resolve_sync("storage")
168 if self.storage is None:
169 self.storage = get_adapter("storage")
170 if self.cache is None:
171 self.cache = _try_resolve_sync("cache")
172 if self.cache is None:
173 self.cache = get_adapter("cache")
174 if not hasattr(self, "config"):
175 self.config = _try_resolve_sync("config")
176 if self.config is None:
177 config_adapter = get_adapter("config")
178 self.config = (
179 config_adapter
180 if hasattr(config_adapter, "model_config")
181 else OneiricSettings()
182 )
184 def get_supported_extensions(self) -> tuple[str, ...]:
185 return ("html", "css", "js")
187 async def _list_templates_for_extensions(
188 self,
189 extensions: tuple[str, ...],
190 ) -> list[str]:
191 found: set[str] = set()
192 for searchpath in self.searchpath:
193 for ext in extensions:
194 async for p in searchpath.rglob(f"*.{ext}"):
195 found.add(str(p))
196 return sorted(found)
198 def _normalize_template(
199 self,
200 environment_or_template: t.Any,
201 template: str | AsyncPath | None = None,
202 ) -> str | AsyncPath:
203 if template is None:
204 template = environment_or_template
205 assert template is not None
206 return template
208 async def _find_template_path_parallel(
209 self,
210 template: str | AsyncPath,
211 ) -> AsyncPath | None:
212 async def check_path(searchpath: AsyncPath) -> AsyncPath | None:
213 path = searchpath / template
214 if await path.is_file():
215 return path
216 return None
218 tasks = [check_path(searchpath) for searchpath in self.searchpath]
219 results = await asyncio.gather(*tasks, return_exceptions=True)
221 for result in results:
222 if isinstance(result, AsyncPath):
223 return result
224 return None
226 async def _find_storage_path_parallel(
227 self,
228 template: str | AsyncPath,
229 ) -> tuple[AsyncPath, AsyncPath] | None:
230 async def check_storage_path(
231 searchpath: AsyncPath,
232 ) -> tuple[AsyncPath, AsyncPath] | None:
233 path = searchpath / template
234 storage_path = Templates.get_storage_path(path)
235 if storage_path and await self.storage.templates.exists(storage_path):
236 return path, storage_path
237 return None
239 tasks = [check_storage_path(searchpath) for searchpath in self.searchpath]
240 results = await asyncio.gather(*tasks, return_exceptions=True)
242 for result in results:
243 if isinstance(result, tuple):
244 return result
245 return None
247 async def _find_cache_path_parallel(
248 self,
249 template: str | AsyncPath,
250 ) -> tuple[AsyncPath, AsyncPath, str] | None:
251 async def check_cache_path(
252 searchpath: AsyncPath,
253 ) -> tuple[AsyncPath, AsyncPath, str] | None:
254 path = searchpath / template if searchpath else AsyncPath(template)
255 storage_path = Templates.get_storage_path(path)
256 cache_key = Templates.get_cache_key(storage_path)
257 if (
258 storage_path
259 and self.cache is not None
260 and await self.cache.exists(cache_key)
261 ):
262 return path, storage_path, cache_key
263 return None
265 tasks = [check_cache_path(searchpath) for searchpath in self.searchpath]
266 results = await asyncio.gather(*tasks, return_exceptions=True)
268 for result in results:
269 if isinstance(result, tuple):
270 return result
271 return None
274class LoaderProtocol(t.Protocol):
275 cache: t.Any
276 config: t.Any
277 storage: t.Any
279 async def get_source_async(
280 self,
281 environment_or_template: t.Any,
282 template: str | AsyncPath | None = None,
283 ) -> tuple[
284 str,
285 str | None,
286 t.Callable[[], bool] | t.Callable[[], t.Awaitable[bool]],
287 ]: ...
289 async def list_templates_async(self) -> list[str]: ...
292class FileSystemLoader(BaseTemplateLoader):
293 async def _check_storage_exists(self, storage_path: AsyncPath) -> bool:
294 if self.storage is not None:
295 return t.cast(bool, await self.storage.templates.exists(storage_path))
296 return False
298 async def _sync_template_file(
299 self,
300 path: AsyncPath,
301 storage_path: AsyncPath,
302 ) -> tuple[bytes, int]:
303 if sync_templates is None or SyncDirection is None or SyncStrategy is None:
304 return await self._sync_from_storage_fallback(path, storage_path)
306 try:
307 strategy = SyncStrategy(
308 backup_on_conflict=False,
309 )
311 template_paths = [path]
312 result = await sync_templates(
313 template_paths=template_paths,
314 strategy=strategy,
315 )
317 resp = await path.read_bytes()
318 local_stat = await path.stat()
319 local_mtime = int(local_stat.st_mtime)
321 debug(f"Template sync result: {result.sync_status} for {path}")
322 return resp, local_mtime
324 except Exception as e:
325 debug(f"Sync action failed for {path}: {e}, falling back to primitive sync")
326 return await self._sync_from_storage_fallback(path, storage_path)
328 async def _sync_from_storage_fallback(
329 self,
330 path: AsyncPath,
331 storage_path: AsyncPath,
332 ) -> tuple[bytes, int]:
333 local_stat = await path.stat()
334 local_mtime = int(local_stat.st_mtime)
335 local_size = local_stat.st_size
336 storage_stat = await self.storage.templates.stat(storage_path)
337 storage_mtime = round(storage_stat.get("mtime"))
338 storage_size = storage_stat.get("size")
340 if local_mtime < storage_mtime and local_size != storage_size:
341 resp = await self.storage.templates.open(storage_path)
342 await path.write_bytes(resp)
343 else:
344 resp = await path.read_bytes()
345 if local_size != storage_size:
346 await self.storage.templates.write(storage_path, resp)
347 return resp, local_mtime
349 async def _read_and_store_template(
350 self,
351 path: AsyncPath,
352 storage_path: AsyncPath,
353 ) -> bytes:
354 try:
355 resp = await path.read_bytes()
356 if self.storage is not None:
357 try:
358 import asyncio
360 await asyncio.wait_for(
361 self.storage.templates.write(storage_path, resp), timeout=5.0
362 )
363 except (TimeoutError, Exception) as e:
364 debug(
365 f"Storage write failed for {storage_path}: {e}, continuing with local file"
366 )
367 return resp
368 except FileNotFoundError:
369 raise TemplateNotFound(path.name)
371 async def _cache_template(self, storage_path: AsyncPath, resp: bytes) -> None:
372 if self.cache is not None:
373 await self.cache.set(Templates.get_cache_key(storage_path), resp)
375 async def get_source_async(
376 self,
377 environment_or_template: t.Any,
378 template: str | AsyncPath | None = None,
379 ) -> SourceType:
380 template = self._normalize_template(environment_or_template, template)
381 path = await self._find_template_path_parallel(template)
382 if path is None:
383 raise TemplateNotFound(str(template))
384 storage_path = Templates.get_storage_path(path)
385 debug(path)
387 fs_exists = await path.exists()
388 storage_exists = await self._check_storage_exists(storage_path)
389 local_mtime = 0
391 if storage_exists and fs_exists and (not self.config.deployed):
392 resp, local_mtime = await self._sync_template_file(path, storage_path)
393 else:
394 resp = await self._read_and_store_template(path, storage_path)
396 await self._cache_template(storage_path, resp)
398 async def uptodate() -> bool:
399 return int((await path.stat()).st_mtime) == local_mtime
401 return (resp.decode(), str(storage_path), uptodate)
403 async def list_templates_async(self) -> list[str]:
404 return await self._list_templates_for_extensions(
405 self.get_supported_extensions(),
406 )
409class StorageLoader(BaseTemplateLoader):
410 async def _check_filesystem_sync_opportunity(
411 self, template: str | AsyncPath, storage_path: AsyncPath
412 ) -> AsyncPath | None:
413 if not self.config or self.config.deployed:
414 return None
416 fs_result = await self._find_template_path_parallel(template)
417 if fs_result and await fs_result.exists():
418 return fs_result
419 return None
421 async def _sync_storage_with_filesystem(
422 self,
423 fs_path: AsyncPath,
424 storage_path: AsyncPath,
425 ) -> tuple[bytes, int]:
426 if sync_templates is None or SyncDirection is None or SyncStrategy is None:
427 resp = await self.storage.templates.open(storage_path)
428 stat = await self.storage.templates.stat(storage_path)
429 return resp, round(stat.get("mtime").timestamp())
431 try:
432 strategy = SyncStrategy(
433 direction=SyncDirection.PULL,
434 backup_on_conflict=False,
435 )
437 result = await sync_templates(
438 template_paths=[fs_path],
439 strategy=strategy,
440 )
442 resp = await fs_path.read_bytes()
443 local_stat = await fs_path.stat()
444 local_mtime = int(local_stat.st_mtime)
446 debug(
447 f"Storage-filesystem sync result: {result.sync_status} for {storage_path}"
448 )
449 return resp, local_mtime
451 except Exception as e:
452 debug(
453 f"Storage sync failed for {storage_path}: {e}, reading from storage only"
454 )
455 resp = await self.storage.templates.open(storage_path)
456 stat = await self.storage.templates.stat(storage_path)
457 return resp, round(stat.get("mtime").timestamp())
459 async def get_source_async(
460 self,
461 environment_or_template: t.Any,
462 template: str | AsyncPath | None = None,
463 ) -> tuple[str, str, t.Callable[[], t.Awaitable[bool]]]:
464 template = self._normalize_template(environment_or_template, template)
465 result = await self._find_storage_path_parallel(template)
466 if result is None:
467 raise TemplateNotFound(str(template))
468 _, storage_path = result
469 debug(storage_path)
471 try:
472 fs_path = await self._check_filesystem_sync_opportunity(
473 template, storage_path
474 )
476 if fs_path:
477 resp, local_mtime = await self._sync_storage_with_filesystem(
478 fs_path, storage_path
479 )
480 else:
481 resp = await self.storage.templates.open(storage_path)
482 local_stat = await self.storage.templates.stat(storage_path)
483 local_mtime = round(local_stat.get("mtime").timestamp())
485 if self.cache is not None:
486 await self.cache.set(Templates.get_cache_key(storage_path), resp)
488 async def uptodate() -> bool:
489 if fs_path and await fs_path.exists():
490 fs_stat = await fs_path.stat()
491 return int(fs_stat.st_mtime) == local_mtime
492 else:
493 storage_stat = await self.storage.templates.stat(storage_path)
494 mtime = storage_stat.get("mtime")
495 if hasattr(mtime, "timestamp"):
496 timestamp = t.cast(float, mtime.timestamp())
497 return round(timestamp) == local_mtime
498 return False
500 return (resp.decode(), str(storage_path), uptodate)
501 except (FileNotFoundError, AttributeError):
502 raise TemplateNotFound(str(template))
504 async def list_templates_async(self) -> list[str]:
505 found: list[str] = []
506 for searchpath in self.searchpath:
507 with suppress(FileNotFoundError):
508 paths = await self.storage.templates.list(
509 Templates.get_storage_path(searchpath),
510 )
511 found.extend(p for p in paths if p.endswith((".html", ".css", ".js")))
512 found.sort()
513 return found
516class RedisLoader(BaseTemplateLoader):
517 async def get_source_async(
518 self,
519 environment_or_template: t.Any,
520 template: str | AsyncPath | None = None,
521 ) -> tuple[str, str | None, t.Callable[[], t.Awaitable[bool]]]:
522 template = self._normalize_template(environment_or_template, template)
523 result = await self._find_cache_path_parallel(template)
524 if result is None:
525 raise TemplateNotFound(str(template))
526 path, _, cache_key = result
527 debug(cache_key)
528 resp = await self.cache.get(cache_key) if self.cache is not None else None
529 if not resp:
530 raise TemplateNotFound(path.name)
532 def uptodate() -> bool:
533 return True
535 return (resp.decode(), None, uptodate)
537 async def list_templates_async(self) -> list[str]:
538 found: list[str] = []
539 for ext in ("html", "css", "js"):
540 scan_result: t.Any = (
541 await self.cache.scan(f"*.{ext}") if self.cache is not None else []
542 )
543 if hasattr(scan_result, "__aiter__"):
544 async for k in scan_result:
545 found.append(k)
546 else:
547 found.extend(scan_result)
548 found.sort()
549 return found
552class PackageLoader(BaseTemplateLoader):
553 _template_root: AsyncPath
554 _adapter: str
555 package_name: str
556 _loader: t.Any
558 def __init__(
559 self,
560 package_name: str,
561 path: str = "templates",
562 adapter: str = "admin",
563 ) -> None:
564 self.package_path = Path(package_name)
565 self.path = self.package_path / path
566 super().__init__(AsyncPath(self.path))
567 self.package_name = package_name
568 self._adapter = adapter
569 self._template_root = AsyncPath(".")
570 try:
571 if package_name.startswith("/"):
572 spec = None
573 self._loader = None
574 return
575 import_module(package_name)
576 spec = find_spec(package_name)
577 if spec is None:
578 msg = f"Could not find package {package_name}"
579 raise ImportError(msg)
580 except ModuleNotFoundError:
581 spec = None
582 self._loader = None
583 return
584 roots: list[Path] = []
585 template_root = None
586 loader = spec.loader
587 self._loader = loader
588 if spec.submodule_search_locations:
589 roots.extend(Path(s) for s in spec.submodule_search_locations)
590 elif spec.origin is not None:
591 roots.append(Path(spec.origin))
592 for root in roots:
593 root = root / path
594 if root.is_dir():
595 template_root = root
596 break
597 if template_root is None:
598 msg = f"The {package_name!r} package was not installed in a way that PackageLoader understands."
599 raise ValueError(
600 msg,
601 )
602 self._template_root = AsyncPath(template_root)
604 async def get_source_async(
605 self,
606 environment_or_template: t.Any,
607 template: str | AsyncPath | None = None,
608 ) -> tuple[str, str, t.Callable[[], t.Awaitable[bool]]]:
609 if template is None:
610 template = environment_or_template
611 assert template is not None
612 template_path: AsyncPath = AsyncPath(template)
613 path = self._template_root / template_path
614 debug(path)
615 if not await path.is_file():
616 raise TemplateNotFound(template_path.name)
617 source = await path.read_bytes()
618 mtime = (await path.stat()).st_mtime
620 async def uptodate() -> bool:
621 return await path.is_file() and (await path.stat()).st_mtime == mtime
623 source = _apply_template_replacements(source, self.config.deployed)
624 storage_path = Templates.get_storage_path(path)
625 _storage_path: list[str] = list(storage_path.parts)
626 _storage_path[0] = "_templates"
627 _storage_path.insert(1, self._adapter)
628 _storage_path.insert(2, getattr(self.config, self._adapter).style)
629 storage_path = AsyncPath("/".join(_storage_path))
630 cache_key = Templates.get_cache_key(storage_path)
631 if self.cache is not None:
632 await self.cache.set(cache_key, source)
633 return (source.decode(), path.name, uptodate)
635 async def list_templates_async(self) -> list[str]:
636 found: set[str] = set()
637 for ext in ("html", "css", "js"):
638 found.update([str(p) async for p in self._template_root.rglob(f"*.{ext}")])
639 return sorted(found)
642class ChoiceLoader(AsyncBaseLoader):
643 loaders: list[AsyncBaseLoader | LoaderProtocol]
645 def __init__(
646 self,
647 loaders: list[AsyncBaseLoader | LoaderProtocol],
648 searchpath: AsyncPath | t.Sequence[AsyncPath] | None = None,
649 ) -> None:
650 super().__init__(searchpath or AsyncPath("templates"))
651 self.loaders = loaders
653 async def get_source_async(
654 self,
655 environment_or_template: t.Any,
656 template: str | AsyncPath | None = None,
657 ) -> SourceType:
658 if template is None:
659 template = environment_or_template
660 assert template is not None
661 for loader in self.loaders:
662 try:
663 result = await loader.get_source_async(
664 environment_or_template, template
665 )
666 return result
667 except TemplateNotFound:
668 continue
669 except Exception: # nosec B112
670 continue
671 raise TemplateNotFound(str(template))
673 async def list_templates_async(self) -> list[str]:
674 found: set[str] = set()
675 for loader in self.loaders:
676 templates = await loader.list_templates_async()
677 found.update(templates)
678 return sorted(found)
681class TemplatesSettings(TemplatesBaseSettings):
682 loader: str | None = None
683 extensions: list[str] = []
684 delimiters: dict[str, str] = {
685 "block_start_string": "[%",
686 "block_end_string": "%]",
687 "variable_start_string": "[[",
688 "variable_end_string": "]]",
689 "comment_start_string": "[#",
690 "comment_end_string": "#]",
691 }
692 globals: dict[str, t.Any] = {}
693 context_processors: list[str] = []
695 def __init__(self, **data: t.Any) -> None:
696 from pydantic import BaseModel
698 BaseModel.__init__(self, **data) # type: ignore[arg-type]
699 if not hasattr(self, "cache_timeout"):
700 self.cache_timeout = 300
701 try:
702 models = _try_resolve_sync("models")
703 self.globals["models"] = models
704 except Exception:
705 self.globals["models"] = None
708class Templates(TemplatesBase):
709 app: AsyncJinja2Templates | None = None
711 def __init__(self, **kwargs: t.Any) -> None:
712 super().__init__(**kwargs)
713 self.filters: dict[str, t.Callable[..., t.Any]] = {}
714 self.enabled_admin = get_adapter("admin")
715 self.enabled_app = self._get_app_adapter()
716 self._admin = None
717 self._admin_initialized = False
719 def _get_app_adapter(self) -> t.Any:
720 app_adapter = get_adapter("app")
721 if app_adapter is not None:
722 return app_adapter
723 with suppress(Exception):
724 app_adapter = depends.get_sync("app")
725 if app_adapter is not None:
726 return app_adapter
728 return None
730 @property
731 def admin(self) -> AsyncJinja2Templates | None:
732 if not self._admin_initialized and self.enabled_admin:
733 import asyncio
735 loop = asyncio.get_event_loop()
736 if (
737 hasattr(self, "_admin_cache")
738 and hasattr(self, "admin_searchpaths")
739 and self.admin_searchpaths is not None
740 ):
741 debug("Initializing admin templates environment")
742 self._admin = loop.run_until_complete(
743 self.init_envs(
744 self.admin_searchpaths,
745 admin=True,
746 cache=self._admin_cache,
747 ),
748 )
749 else:
750 debug(
751 "Skipping admin templates initialization - missing cache or searchpaths"
752 )
753 self._admin_initialized = True
754 return self._admin
756 @admin.setter
757 def admin(self, value: AsyncJinja2Templates | None) -> None:
758 self._admin = value
759 self._admin_initialized = True
761 def get_loader(self, template_paths: list[AsyncPath]) -> ChoiceLoader:
762 searchpaths: list[AsyncPath] = []
763 for path in template_paths:
764 searchpaths.extend([path, path / "blocks"])
765 loaders: list[AsyncBaseLoader] = [
766 RedisLoader(searchpaths),
767 StorageLoader(searchpaths),
768 ]
769 file_loaders: list[AsyncBaseLoader | LoaderProtocol] = [
770 FileSystemLoader(searchpaths),
771 ]
772 jinja_loaders: list[AsyncBaseLoader | LoaderProtocol] = loaders + file_loaders
773 if not self.config.deployed and (not self.config.debug.production):
774 jinja_loaders = file_loaders + loaders
775 if self.enabled_admin and template_paths == self.admin_searchpaths:
776 jinja_loaders.append(
777 PackageLoader(self.enabled_admin.name, "templates", "admin"),
778 )
779 debug(jinja_loaders)
780 return ChoiceLoader(jinja_loaders)
782 async def init_envs(
783 self,
784 template_paths: list[AsyncPath],
785 admin: bool = False,
786 cache: t.Any | None = None,
787 ) -> AsyncJinja2Templates:
788 _extensions: list[t.Any] = [loopcontrols, i18n, jinja_debug]
789 _imported_extensions = [
790 import_module(e) for e in self.config.templates.extensions
791 ]
792 for e in _imported_extensions:
793 _extensions.extend(
794 [
795 v
796 for v in vars(e).values()
797 if isclass(v)
798 and v.__name__ != "Extension"
799 and issubclass(v, Extension)
800 ],
801 )
802 bytecode_cache = None
803 if cache is not None:
804 bytecode_cache = AsyncRedisBytecodeCache(prefix="bccache", client=cache)
805 context_processors: list[t.Callable[..., t.Any]] = []
806 for processor_path in self.config.templates.context_processors:
807 module_path, func_name = processor_path.rsplit(".", 1)
808 module = import_module(module_path)
809 processor = getattr(module, func_name)
810 context_processors.append(processor)
811 templates = AsyncJinja2Templates(
812 directory=AsyncPath("templates"),
813 context_processors=context_processors,
814 extensions=_extensions,
815 bytecode_cache=bytecode_cache,
816 enable_async=True,
817 )
818 loader = self.get_loader(template_paths)
819 if loader:
820 templates.env.loader = loader
821 elif self.config.templates.loader:
822 templates.env.loader = literal_eval(self.config.templates.loader)
823 for delimiter, value in self.config.templates.delimiters.items():
824 setattr(templates.env, delimiter, value)
825 # Type cast globals dict to avoid assignment type errors
826 globals_dict: dict[str, t.Any] = templates.env.globals # type: ignore[assignment]
827 globals_dict["config"] = self.config
828 globals_dict["render_block"] = templates.render_block
829 globals_dict["render_component"] = self._get_htmy_component_renderer()
830 if admin:
831 try:
832 from sqladmin.helpers import ( # type: ignore[import-not-found,import-untyped]
833 get_object_identifier,
834 )
835 except ImportError:
836 get_object_identifier = str
837 globals_dict["min"] = min
838 globals_dict["zip"] = zip
839 globals_dict["admin"] = self
840 globals_dict["is_list"] = lambda x: isinstance(x, list)
841 globals_dict["get_object_identifier"] = get_object_identifier
842 for k, v in self.config.templates.globals.items():
843 globals_dict[k] = v
844 return templates
846 def _resolve_cache(self, cache: t.Any | None) -> t.Any | None:
847 if cache is None:
848 cache = _try_resolve_sync("cache")
849 return cache
851 async def _setup_admin_templates(self, cache: t.Any | None) -> None:
852 if self.enabled_admin:
853 self.admin_searchpaths = await self.get_searchpaths(self.enabled_admin)
854 self._admin_cache = cache
856 def _log_loader_info(self) -> None:
857 if self.app and self.app.env.loader and hasattr(self.app.env.loader, "loaders"):
858 for loader in self.app.env.loader.loaders:
859 self.logger.debug(f"{loader.__class__.__name__} initialized")
861 def _log_extension_info(self) -> None:
862 if self.app and hasattr(self.app.env, "extensions"):
863 for ext in self.app.env.extensions:
864 self.logger.debug(f"{ext.split('.')[-1]} loaded")
866 async def _clear_debug_cache(self, cache: t.Any | None) -> None:
867 if getattr(self.config.debug, "templates", False):
868 try:
869 for namespace in (
870 "templates",
871 "_templates",
872 "bccache",
873 "template",
874 "test",
875 ):
876 if cache is not None:
877 await cache.clear(namespace)
878 self.logger.debug("Template caches cleared")
879 with suppress(Exception):
880 htmy_adapter = await depends.resolve("fastblocks", "htmy")
881 if htmy_adapter:
882 await htmy_adapter.clear_component_cache()
883 self.logger.debug("HTMY component caches cleared via adapter")
884 except (NotImplementedError, AttributeError) as e:
885 self.logger.debug(f"Cache clear not supported: {e}")
887 def _get_htmy_component_renderer(self) -> t.Callable[..., t.Any]:
888 async def render_component(
889 component_name: str,
890 context: dict[str, t.Any] | None = None,
891 **kwargs: t.Any,
892 ) -> str:
893 try:
894 htmy_adapter = await depends.resolve("fastblocks", "htmy")
895 if htmy_adapter:
896 htmy_adapter.jinja_templates = self
898 response = await htmy_adapter.render_component(
899 request=None,
900 component=component_name,
901 context=context,
902 **kwargs,
903 )
904 return (
905 response.body.decode()
906 if hasattr(response.body, "decode")
907 else str(response.body)
908 )
909 else:
910 debug(
911 f"HTMY adapter not available for component '{component_name}'"
912 )
913 return f"<!-- HTMY adapter not available for '{component_name}' -->"
914 except Exception as e:
915 debug(
916 f"Failed to render component '{component_name}' via HTMY adapter: {e}"
917 )
918 return f"<!-- Error rendering component '{component_name}': {e} -->"
920 return render_component
922 async def init(self, cache: t.Any | None = None) -> None:
923 cache = self._resolve_cache(cache)
924 app_adapter = self.enabled_app
925 if app_adapter is None:
926 app_adapter = _try_resolve_sync("app")
927 if app_adapter:
928 debug("Retrieved app adapter from dependency injection")
929 else:
930 try:
931 from ..app.default import App
933 app_adapter = _try_resolve_sync("app") or App()
934 debug("Created app adapter by direct import")
935 register_candidate(
936 depends,
937 domain="fastblocks",
938 key="app",
939 factory=lambda: app_adapter,
940 metadata={"name": "app", "category": "app"},
941 )
942 except Exception:
943 from types import SimpleNamespace as SimpleNamespace
945 app_adapter = SimpleNamespace(name="app", category="app")
946 debug(
947 "Created fallback app adapter - discovery failed, direct import failed"
948 )
949 self.app_searchpaths = await self.get_searchpaths(app_adapter)
950 self.app = await self.init_envs(self.app_searchpaths, cache=cache)
951 register_candidate(
952 depends,
953 domain="fastblocks",
954 key="templates",
955 factory=lambda: self,
956 metadata={
957 "class": "Templates",
958 "module": "fastblocks.adapters.templates.jinja2",
959 },
960 )
961 self._admin = None
962 self._admin_initialized = False
963 await self._setup_admin_templates(cache)
964 self._log_loader_info()
965 self._log_extension_info()
966 await self._clear_debug_cache(cache)
968 @staticmethod
969 def get_attr(html: str, attr: str) -> str | None:
970 parser = HTMLParser()
971 parser.feed(html)
972 soup = parser.get_starttag_text()
973 if soup is None:
974 return None
975 attr_pattern = _get_attr_pattern(attr)
976 _attr = f"{attr}="
977 for s in soup.split():
978 if attr_pattern.search(s):
979 return s.replace(_attr, "").strip('"')
980 return None
982 def _add_filters(self, env: t.Any) -> None:
983 if hasattr(self, "filters") and self.filters:
984 for name, filter_func in self.filters.items():
985 if hasattr(env, "add_filter"):
986 env.add_filter(filter_func, name)
987 else:
988 env.filters[name] = filter_func
990 @track_template_render
991 async def render_template(
992 self,
993 request: t.Any,
994 template: str,
995 context: dict[str, t.Any] | None = None,
996 status_code: int = 200,
997 headers: dict[str, str] | None = None,
998 ) -> t.Any:
999 if context is None:
1000 context = {}
1001 if headers is None:
1002 headers = {}
1004 templates_env = self.app
1005 if templates_env:
1006 return await templates_env.TemplateResponse(
1007 request=request,
1008 name=template,
1009 context=context,
1010 status_code=status_code,
1011 headers=headers,
1012 )
1013 from starlette.responses import HTMLResponse
1015 return HTMLResponse(
1016 content=f"<html><body>Template {template} not found</body></html>",
1017 status_code=404,
1018 headers=headers,
1019 )
1021 @track_template_render
1022 async def render_component(
1023 self,
1024 request: t.Any,
1025 component: str,
1026 context: dict[str, t.Any] | None = None,
1027 status_code: int = 200,
1028 headers: dict[str, str] | None = None,
1029 **kwargs: t.Any,
1030 ) -> t.Any:
1031 try:
1032 htmy_adapter = await depends.resolve("fastblocks", "htmy")
1033 if htmy_adapter:
1034 htmy_adapter.jinja_templates = self
1035 return await htmy_adapter.render_component(
1036 request=request,
1037 component=component,
1038 context=context,
1039 status_code=status_code,
1040 headers=headers,
1041 **kwargs,
1042 )
1043 else:
1044 from starlette.responses import HTMLResponse
1046 return HTMLResponse(
1047 content=f"<html><body>HTMY adapter not available for component '{component}'</body></html>",
1048 status_code=500,
1049 headers=headers,
1050 )
1051 except Exception as e:
1052 from starlette.responses import HTMLResponse
1054 return HTMLResponse(
1055 content=f"<html><body>Component error: {e}</body></html>",
1056 status_code=500,
1057 headers=headers,
1058 )
1060 def filter(
1061 self,
1062 name: str | None = None,
1063 ) -> t.Callable[[t.Callable[..., t.Any]], t.Callable[..., t.Any]]:
1064 def decorator(f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
1065 if self.app and hasattr(self.app.env, "filters"):
1066 self.app.env.filters[name or f.__name__] = f
1067 if self.admin and hasattr(self.admin.env, "filters"):
1068 self.admin.env.filters[name or f.__name__] = f
1069 return f
1071 return decorator
1073 def _load_extensions(self) -> list[t.Any]:
1074 _extensions: list[t.Any] = [loopcontrols, i18n, jinja_debug]
1075 extensions_list = getattr(
1076 getattr(self, "settings", None),
1077 "extensions",
1078 self.config.templates.extensions,
1079 )
1080 _imported_extensions = [import_module(e) for e in extensions_list]
1081 for e in _imported_extensions:
1082 _extensions.extend(
1083 [
1084 v
1085 for v in vars(e).values()
1086 if isclass(v)
1087 and v.__name__ != "Extension"
1088 and issubclass(v, Extension)
1089 ],
1090 )
1091 return _extensions
1094MODULE_ID = UUID("01937d86-4f2a-7b3c-8d9e-1234567890ab")
1095MODULE_STATUS = AdapterStatus.STABLE
1097with suppress(Exception):
1098 depends.set(Templates)
1100# Oneiric migration indicator
1101_using_oneiric = True
1103__all__ = ["Templates", "TemplatesSettings"]