BaseRequestHandler はいかがでしょう?
テンプレートエンジンで扱う HTML ファイル群は、一つのディレクトリ内にまとめて格納しておきたい。
その場合、webapp.RequestHandler のサブクラスとして BaseRequestHandler が提案されています。
以下では、templates ディレクトリを作成して HTML ファイルを格納することができます。
# # base_request_handler.py # import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template class BaseRequestHandler(webapp.RequestHandler): """Base request handler extends webapp.Request handler It defines the generate method, which renders a Django template in response to a web request """ def generate(self, template_name, template_values={}): """Generate takes renders and HTML template along with values passed to that template Args: template_name: A string that represents the name of the HTML template template_values: A dictionary that associates objects with a string assigned to that object to call in the HTML template. The defualt is an empty dictionary. """ # Construct the path to the template directory = os.path.dirname(__file__) path = os.path.join(directory, 'templates', template_name) # Respond to the request by rendering the template self.response.out.write(template.render(path, template_values))
Google のサンプルコードにも見受けられます(line 112)。
(html ディレクトリに格納したい場合、'templates' を 'html' に変えてください)
各ページリクエストハンドラでは、この BaseRequestHandler を継承して generate() メソッドを呼び出します。
# # main_page_handler.py # from base_request_handler import BaseRequestHandler class MainPageHandler(BaseRequestHandler): def get(self): template_name = 'index.html' # HTML file name template_values = {} self.generate(template_name, template_values)
- おまけ
私は(個人的に)これらの間に、以下のような抽象クラス PageHandler を使っています。 この場合、MainPageHandler は PageHandler のサブクラスになります。
# # page_handler.py # from base_request_handler import BaseRequestHandler class PageHandler(BaseRequestHandler): def __init__(self): super(PageHandler, self).__init__() self.template_values = {} self.template_name = '' # HTML file name def get(self): self.generate(self.template_name, self.template_values)