cache_extension.py
This file
Path
docs/cache_extension.py
56 lines · 2.1 KiB · Python
Last changed by
Merge pull request #450 from jenisys/fixdoc.extension_exampleMarkus Unterwaditzerbefore adoptiond2ffef5
History of this fileTake it
The walk stopped after 200 commits: lines older than 41746b9 point at it.
Some more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 1–22why, one step back1from jinja2 import nodes2from jinja2.ext import Extension345class FragmentCacheExtension(Extension):6 # a set of names that trigger the extension.7 tags = set(['cache'])89 def __init__(self, environment):10 super(FragmentCacheExtension, self).__init__(environment)1112 # add the defaults to the environment13 environment.extend(14 fragment_cache_prefix='',15 fragment_cache=None16 )1718 def parse(self, parser):19 # the first token is the token that started the tag. In our case20 # we only listen to ``'cache'`` so this will be a name token with21 # `cache` as value. We get the line number so that we can give22 # that line number to the nodes we create by hand.Merge pull request #450 from jenisys/fixdoc.extension_exampleMarkus Unterwaditzerbefore adoptiond2ffef5
line 23why, one step back23 lineno = next(parser.stream).linenoSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 24–56why, one step back2425 # now we parse a single expression that is used as cache key.26 args = [parser.parse_expression()]2728 # if there is a comma, the user provided a timeout. If not use29 # None as second parameter.30 if parser.stream.skip_if('comma'):31 args.append(parser.parse_expression())32 else:33 args.append(nodes.Const(None))3435 # now we parse the body of the cache block up to `endcache` and36 # drop the needle (which would always be `endcache` in that case)37 body = parser.parse_statements(['name:endcache'], drop_needle=True)3839 # now return a `CallBlock` node that calls our _cache_support40 # helper method on this extension.41 return nodes.CallBlock(self.call_method('_cache_support', args),42 [], [], body).set_lineno(lineno)4344 def _cache_support(self, name, timeout, caller):45 """Helper callback."""46 key = self.environment.fragment_cache_prefix + name4748 # try to load the block from the cache49 # if there is no fragment in the cache, render it and store50 # it in the cache.51 rv = self.environment.fragment_cache.get(key)52 if rv is not None:53 return rv54 rv = caller()55 self.environment.fragment_cache.add(key, rv, timeout)56 return rv