Skip to content

Instantly share code, notes, and snippets.

@kwatch
Created September 5, 2015 03:01
Show Gist options
  • Save kwatch/132d7267df7149165960 to your computer and use it in GitHub Desktop.
Save kwatch/132d7267df7149165960 to your computer and use it in GitHub Desktop.
テンプレートオブジェクトをキャッシュするサンプルコード
# -*- coding: utf-8 -*-
###
### テンプレートオブジェクトをキャッシュするサンプルコード
###
from os.path import getmtime
class TemplateError(Exception):
pass
class TemplateManager(object):
def __init__(self):
self._cache = {} ## { filename: (mtime, template) }
def get_template(self, filename):
## キャッシュがあり、かつtimestampが変わってなければ、それを使う
mtime = getmtime(filename)
pair = self._cache.get(filename)
if pair and pair[0] == mtime:
template = pair[1]
## そうでなければ、テンプレートをコンパイルしてキャッシュする
## (コンパイル中にテンプレートファイルが更新されてたらリトライ)
else:
template = Template.compile(filename)
mtime2 = getmtime(filename)
if mtime != mtime2:
template = Template.compile(filename)
if mtime2 != getmtime(filename):
raise TemplateError("%s: failed to compile" % filename)
self._cache[filename] = (mtime, template)
return template
## グローバル変数だ!
manager = TemplateManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment