Coverage for fastblocks/adapters/templates/_filters.py: 0%

49 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-21 04:50 -0700

1import hashlib 

2import typing as t 

3from urllib.parse import quote_plus 

4 

5from acb.config import Config 

6from acb.depends import depends 

7from fastblocks.actions.minify import minify 

8 

9_minification_cache = {} 

10_cache_max_size = 1000 

11 

12 

13def _cached_minify( 

14 content: str, 

15 minify_func: t.Callable[[str], str | bytes | bytearray], 

16 cache_prefix: str, 

17) -> str | bytes | bytearray: 

18 content_hash = hashlib.md5(content.encode(), usedforsecurity=False).hexdigest() 

19 cache_key = f"{cache_prefix}:{content_hash}" 

20 

21 if cache_key in _minification_cache: 

22 return _minification_cache[cache_key] 

23 

24 result = minify_func(content) 

25 

26 if len(_minification_cache) >= _cache_max_size: 

27 oldest_key = next(iter(_minification_cache)) 

28 del _minification_cache[oldest_key] 

29 

30 _minification_cache[cache_key] = result 

31 return result 

32 

33 

34class Filters: 

35 config: Config = depends() 

36 

37 @classmethod 

38 def get_templates(cls) -> t.Any: 

39 if not hasattr(cls, "_templates"): 

40 cls._templates = depends.get("templates") 

41 return cls._templates 

42 

43 @staticmethod 

44 def map_src(address: str) -> str: 

45 return quote_plus(address) 

46 

47 @staticmethod 

48 def url_encode(text: str) -> str: 

49 return quote_plus(text) 

50 

51 @staticmethod 

52 def minify_html(html: str) -> str | bytes | bytearray: 

53 return _cached_minify(html, minify.html, "html") 

54 

55 @staticmethod 

56 def minify_js(js: str) -> bytearray | bytes | str: 

57 return _cached_minify(js, minify.js, "js") 

58 

59 @staticmethod 

60 def minify_css(css: str) -> bytearray | bytes | str: 

61 return _cached_minify(css, minify.css, "css") 

62 

63 @classmethod 

64 def register_filters(cls) -> None: 

65 templates = cls.get_templates() 

66 templates.filter()(cls.map_src) 

67 templates.filter()(cls.url_encode) 

68 templates.filter()(cls.minify_html) 

69 templates.filter()(cls.minify_js) 

70 templates.filter()(cls.minify_css)