使用GAE Memcache API缓存预渲染模板

时间:2011-04-24 15:39:49

标签: python google-app-engine

我一直在使用此逻辑在我的GAE应用程序中呈现templates

path = os.path.join(os.path.dirname(__file__), 'page.html')
self.response.out.write(template.render(path, template_values))

我想知道是否可以(并且更有效)加载未渲染的模板文本并将其存储在Memcache中。 template.render()方法似乎需要文件路径,这是否可能?

编辑:为清楚起见,我说的是缓存模板本身,而不是渲染输出。

1 个答案:

答案 0 :(得分:3)

Google App Engine会立即缓存模板,以确保您的应用程序响应。

以下是源代码中可用的template.py模块的有趣部分:

def render(template_path, template_dict, debug=False):
  """Renders the template at the given path with the given dict of values."""
  t = load(template_path, debug)
  return t.render(Context(template_dict))

template_cache = {}
def load(path, debug=False):
  abspath = os.path.abspath(path)

  if not debug:
    template = template_cache.get(abspath, None) # <---- CACHING!
  else:
    template = None

  if not template:
    directory, file_name = os.path.split(abspath)
    ...

正如您所看到的,唯一要记住的是避免在生产中设置debug = True