Created
September 5, 2015 03:01
-
-
Save kwatch/132d7267df7149165960 to your computer and use it in GitHub Desktop.
テンプレートオブジェクトをキャッシュするサンプルコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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