Debian Codegraph @

src/flask_caching/jinja2ext.py

raw
1 """
2 flask_caching.jinja2ext
3 ~~~~~~~~~~~~~~~~~~~~~~~
4
5 Jinja2 extension that adds support for caching template fragments.
6
7 Usage::
8
9 {% cache timeout key1[, [key2, ...]] %}
10 ...
11 {% endcache %}
12
13 By default, the value of "path to template file" + "block start line"
14 is used as the cache key. Also, the key name can be set manually.
15 Keys are concatenated together into a single string, that can be used
16 to avoid the same block evaluating in different templates.
17
18 Set the timeout to ``None`` for no timeout, but with custom keys::
19
20 {% cache None "key" %}
21 ...
22 {% endcache %}
23
24 Set the timeout to ``del`` to delete the cached value::
25
26 {% cache 'del' key1 %}
27 ...
28 {% endcache %}
29
30 Considering we have ``render_form_field`` and ``render_submit`` macros::
31
32 {% cache 60*5 'myform' %}
33 <div>
34 <form>
35 {% render_form_field(form.username) %}
36 {% render_submit() %}
37 </form>
38 </div>
39 {% endcache %}
40
41 :copyright: (c) 2010 by Thadeus Burgess.
42 :license: BSD, see LICENSE for more details.
43 """
44
45 from collections.abc import Callable
46 from typing import Any
47
48 from jinja2 import nodes
49 from jinja2.ext import Extension
50 from jinja2.parser import Parser
51
52 from flask_caching import make_template_fragment_key
53 from flask_caching.utils import _Timeout
54 from flask_caching.utils import normalize_timeout
55
56 JINJA_CACHE_ATTR_NAME = "_template_fragment_cache"
57
58
59 class CacheExtension(Extension):
60 tags = {"cache"}
61
62 def parse(self, parser: Parser) -> nodes.Node:
63 lineno = next(parser.stream).lineno
64
65 #: Parse timeout
66 args = [parser.parse_expression()]
67
68 #: Parse fragment name
69 #: Grab the fragment name if it exists
70 #: otherwise, default to the old method of using the template's
71 #: lineno to maintain backwards compatibility.
72 if parser.stream.skip_if("comma"):
73 args.append(parser.parse_expression())
74 else:
75 args.append(nodes.Const(f"{parser.filename}{lineno}"))
76
77 #: Parse vary_on parameters
78 vary_on: list[nodes.Expr] = []
79 while parser.stream.skip_if("comma"):
80 vary_on.append(parser.parse_expression())
81
82 if vary_on:
83 args.append(nodes.List(vary_on))
84 else:
85 args.append(nodes.Const([]))
86
87 body = parser.parse_statements(("name:endcache",), drop_needle=True)
88 return nodes.CallBlock(
89 self.call_method("_cache", args), [], [], body
90 ).set_lineno(lineno)
91
92 def _cache(
93 self,
94 timeout: _Timeout | str | None,
95 fragment_name: str,
96 vary_on: list[str],
97 caller: Callable[[], str],
98 ) -> Any:
99 cache = getattr(self.environment, JINJA_CACHE_ATTR_NAME)
100 key = make_template_fragment_key(fragment_name, vary_on=vary_on)
101
102 #: Delete key if timeout is 'del'
103 if timeout == "del":
104 try:
105 cache.delete(key)
106 return caller()
107 except Exception as e:
108 if cache.app.debug:
109 raise e
110 else:
111 return caller()
112
113 try:
114 rv = cache.get(key)
115 if rv is None:
116 rv = caller()
117 seconds = normalize_timeout(timeout)
118 cache.set(key, rv, timeout=seconds)
119 return rv
120 except Exception as e:
121 if cache.app.debug:
122 raise e
123 else:
124 return caller()