Coverage for an_website/utils/template_loader.py: 100.000%

16 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-06-10 18:56 +0000

1# This program is free software: you can redistribute it and/or modify 

2# it under the terms of the GNU Affero General Public License as 

3# published by the Free Software Foundation, either version 3 of the 

4# License, or (at your option) any later version. 

5# 

6# This program is distributed in the hope that it will be useful, 

7# but WITHOUT ANY WARRANTY; without even the implied warranty of 

8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

9# GNU Affero General Public License for more details. 

10# 

11# You should have received a copy of the GNU Affero General Public License 

12# along with this program. If not, see <https://www.gnu.org/licenses/>. 

13 

14"""A Tornado template loader.""" 

15 

16import os.path 

17from importlib.resources.abc import Traversable 

18from typing import override 

19 

20from tornado.template import BaseLoader, Template 

21 

22 

23class TemplateLoader(BaseLoader): 

24 """A Tornado template loader.""" 

25 

26 root: Traversable 

27 

28 def __init__(self, root: Traversable, whitespace: None | str) -> None: 

29 """Initialize the template loader.""" 

30 self.root = root 

31 super().__init__(whitespace=whitespace) 

32 

33 @override 

34 def _create_template(self, name: str) -> Template: 

35 """Create a template from the given name.""" 

36 return Template((self.root / name).read_bytes(), name=name, loader=self) 

37 

38 @override 

39 def resolve_path(self, name: str, parent_path: str | None = None) -> str: 

40 """Resolve the template path. 

41 

42 name is interpreted as relative to parent_path if it's not None. 

43 """ 

44 if ( 

45 # same check as in tornado.template.Loader 

46 parent_path 

47 and not parent_path.startswith("<") 

48 and not parent_path.startswith("/") 

49 and not name.startswith("/") 

50 ): 

51 return os.path.normpath( 

52 os.path.join(os.path.dirname(parent_path), name) 

53 ) 

54 return name