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 timeout to ``del`` to delete 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 jinja2 import nodes
46 from jinja2.ext import Extension
47
48 from flask_caching import make_template_fragment_key
49
50 JINJA_CACHE_ATTR_NAME = "_template_fragment_cache"
51
52
53 class CacheExtension(Extension):
54 tags = {"cache"}
55
56 def parse(self, parser):
57 lineno = next(parser.stream).lineno
58
59 #: Parse timeout
60 args = [parser.parse_expression()]
61
62 #: Parse fragment name
63 #: Grab the fragment name if it exists
64 #: otherwise, default to the old method of using the templates
65 #: lineno to maintain backwards compatibility.
66 if parser.stream.skip_if("comma"):
67 args.append(parser.parse_expression())
68 else:
69 args.append(nodes.Const(f"{parser.filename}{lineno}"))
70
71 #: Parse vary_on parameters
72 vary_on = []
73 while parser.stream.skip_if("comma"):
74 vary_on.append(parser.parse_expression())
75
76 if vary_on:
77 args.append(nodes.List(vary_on))
78 else:
79 args.append(nodes.Const([]))
80
81 body = parser.parse_statements(["name:endcache"], drop_needle=True)
82 return nodes.CallBlock(
83 self.call_method("_cache", args), [], [], body
84 ).set_lineno(lineno)
85
86 def _cache(self, timeout, fragment_name, vary_on, caller):
87 try:
88 cache = getattr(self.environment, JINJA_CACHE_ATTR_NAME)
89 except AttributeError as e:
90 raise e
91
92 key = make_template_fragment_key(fragment_name, vary_on=vary_on)
93
94 #: Delete key if timeout is 'del'
95 if timeout == "del":
96 cache.delete(key)
97 return caller()
98
99 rv = cache.get(key)
100 if rv is None:
101 rv = caller()
102 cache.set(key, rv, timeout)
103 return rv