Coverage for gramex\transforms\template.py: 94%

# Coverage for gramex\transforms\template.py : 94%

## 26 statements 26 run 0 missing 0 excluded 2 partial

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 import os

2 import tornado.gen

3 import tornado.template

4 import gramex.cache

5

6

7 class CacheLoader(tornado.template.Loader):

8 def load(self, name, parent_path=None):

9 # Identical to tornado.template.Loader.load, but ALWAYS creates

10 # template, even if it's cached -- because _create_template caches it

11 name = self.resolve_path(name, parent_path=parent_path)

12 with self.lock:

13 self.templates[name] = self._create_template(name)

14 return self.templates[name]

15

16 def _template_opener(self, path):

17 with open(path, 'rb') as f:

18 return tornado.template.Template(f.read(), name=self._name, loader=self)

19

20 def _create_template(self, name):

21 # Use gramex.cache.open to ensure that the file is cached

22 self._name = name

23 return gramex.cache.open(os.path.join(self.root, name), self._template_opener)

24

25

26@tornado.gen.coroutine

27 def template(content, handler=None, **kwargs):

28 '''

29 Renders template from content. Used as a transform in any handler, mainly

30 FileHandler.

31 '''

32 loader = None

33 if handler is not None and getattr(handler, 'path', None): 33 ↛ 35line 33 didn't jump to line 35, because the condition on line 33 was never false

34 loader = CacheLoader(os.path.dirname(str(handler.file)))

35 tmpl = tornado.template.Template(content, loader=loader)

36

37 if handler is not None: 37 ↛ 42line 37 didn't jump to line 42, because the condition on line 37 was never false

38 for key, val in handler.get_template_namespace().items():

39 kwargs.setdefault(key, val)

40

41 # handler is added to kwargs by handler.get_template_namespace()

42 raise tornado.gen.Return(tmpl.generate(**kwargs).decode('utf-8'))