python / expert
Snippet
Django Template Loader mit Custom Namespace und Caching-Strategie
Custom Template Loader erweitern Djangos Template-Ladepipeline mit Namespace-Auflösung und In-Memory-Caching. Durch Implementierung der Loader-Schnittstelle und Überschreiben von get_template_sources aktivierst du namespaced Template-Auflösung (Namespace:Template Syntax). Der MD5-basierte Cache-Key gewährleistet effizientes Template-Caching, während der einstündige Timeout Frische mit Performancegewinnen ausbalanciert.
snippet.py
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
import hashlibfrom django.template import TemplateDoesNotExistfrom django.template.loaders.base import Loaderfrom django.core.cache import cacheclass CachedNamespaceLoader(Loader):def __init__(self, engine, dirs, namespaces):super().__init__(engine, dirs)self.namespaces = namespaces or {}self._template_cache = {}def get_template_sources(self, template_name):namespace, _, template = template_name.partition(':')if namespace in self.namespaces:base_dirs = self.namespaces[namespace]for dir in base_dirs:try:yield self.get_template_path(f'{template}', dir)except FileNotFoundError:continuedef get_contents(self, origin):cache_key = f'template:{hashlib.md5(origin.name.encode()).hexdigest()}'template_source = cache.get(cache_key)if template_source is None:template_source = super().get_contents(origin)cache.set(cache_key, template_source, timeout=3600)return template_sourcedef get_template_path(self, template_name, dir):path = f'{dir}/{template_name}'if not os.path.exists(path):raise FileNotFoundError(f'Template {path} not found')return path
django
Erklärung
1
class CachedNamespaceLoader(Loader):
Erweitert Djangos basischen Loader mit eigener Ladelogik
2
namespace, _, template = template_name.partition(':')
Teilt Namespace:Template Syntax für benutzerdefinierte Auflösung
3
cache_key = f'template:{hashlib.md5(origin.name.encode()).hexdigest()}'
Erstellt deterministischen Cache-Key aus Template-Pfad-Hash
4
cache.set(cache_key, template_source, timeout=3600)
Cacht kompilierten Template-Source für eine Stunde
5
yield self.get_template_path(f'{template}', dir)
Yield aufgelösten Template-Pfad für jedes Namespace-Verzeichnis