OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 import json |
| 6 import logging |
| 7 import os |
| 8 import time |
| 9 |
| 10 from third_party.handlebar import Handlebar |
| 11 |
| 12 class TemplateDataSource(object): |
| 13 def __init__(self, fetcher, base_paths, cache_timeout_seconds): |
| 14 logging.info('Template data source created: %s %d' % |
| 15 (' '.join(base_paths), cache_timeout_seconds)) |
| 16 self._fetcher = fetcher |
| 17 self._template_cache = {} |
| 18 self._base_paths = base_paths |
| 19 self._cache_timeout_seconds = cache_timeout_seconds |
| 20 |
| 21 def Render(self, template_name, context): |
| 22 """This method will render a template named |template_name|, fetching all |
| 23 the partial templates needed with |self._fetcher|. Partials are retrieved |
| 24 from the TemplateDataSource with the |get| method. |
| 25 """ |
| 26 template = self.get(template_name) |
| 27 if not template: |
| 28 return '' |
| 29 # TODO error handling |
| 30 return template.render(json.loads(context), {'templates': self}).text |
| 31 |
| 32 class _CachedTemplate(object): |
| 33 def __init__(self, template, expiry): |
| 34 self.template = template |
| 35 self._expiry = expiry |
| 36 |
| 37 def HasExpired(self): |
| 38 return time.time() > self._expiry |
| 39 |
| 40 def __getitem__(self, key): |
| 41 return self.get(key) |
| 42 |
| 43 def get(self, key): |
| 44 index = key.rfind('.html') |
| 45 if index > 0: |
| 46 key = key[:index] |
| 47 path = key + '.html' |
| 48 if key in self._template_cache: |
| 49 if self._template_cache[key].HasExpired(): |
| 50 self._template_cache.pop(key) |
| 51 if key not in self._template_cache: |
| 52 logging.info('Template cache miss for: ' + path) |
| 53 compiled_template = None |
| 54 for base_path in self._base_paths: |
| 55 try: |
| 56 template = self._fetcher.FetchResource(base_path + path).content |
| 57 compiled_template = Handlebar(template) |
| 58 self._template_cache[key] = self._CachedTemplate( |
| 59 compiled_template, |
| 60 time.time() + self._cache_timeout_seconds) |
| 61 break |
| 62 except: |
| 63 pass |
| 64 |
| 65 return compiled_template |
OLD | NEW |