template_data_source.py revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
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
5import logging
6import posixpath
7import traceback
8
9from data_source import DataSource
10from docs_server_utils import FormatKey
11from extensions_paths import (
12    ARTICLES_TEMPLATES, INTROS_TEMPLATES, PRIVATE_TEMPLATES)
13from file_system import FileNotFoundError
14from future import All
15from path_util import AssertIsDirectory
16
17
18class TemplateDataSource(DataSource):
19  '''Provides a DataSource interface for compiled templates.
20  '''
21  def __init__(self, server_instance, request=None):
22    self._dir = type(self)._BASE
23    AssertIsDirectory(self._dir)
24    self._request = request
25    self._template_cache = server_instance.compiled_fs_factory.ForTemplates(
26        server_instance.host_file_system_provider.GetMaster())
27    self._file_system = server_instance.host_file_system_provider.GetMaster()
28
29  def get(self, path):
30    try:
31      return self._template_cache.GetFromFile('%s%s' %
32          (self._dir, FormatKey(path))).Get()
33    except FileNotFoundError:
34      logging.warning(traceback.format_exc())
35      return None
36
37  def Refresh(self, path):
38    futures = []
39    for root, _, files in self._file_system.Walk(self._dir):
40      futures += [self._template_cache.GetFromFile(
41                      posixpath.join(self._dir, root, FormatKey(f)))
42                  for f in files
43                  if posixpath.splitext(f)[1] == '.html']
44    return All(futures)
45
46
47class ArticleDataSource(TemplateDataSource):
48  '''Serves templates for Articles.
49  '''
50  _BASE = ARTICLES_TEMPLATES
51
52
53class IntroDataSource(TemplateDataSource):
54  '''Serves templates for Intros.
55  '''
56  _BASE = INTROS_TEMPLATES
57
58
59class PartialDataSource(TemplateDataSource):
60  '''Serves templates for private templates.
61  '''
62  _BASE = PRIVATE_TEMPLATES
63