templateの導入

このままPythonのファイルにつらつらとHTMLを書き続けるのも問題なので、PythonのコードとHTMLとを分離します。Google App Engineでは、DjangoPython製の著名なWebフレームワークのひとつ)のtemplateライブラリが設定の必要なく使えるようなので、これを使ってみることにします。

まず、HTML表示を担うファイルを格納するために、templatesフォルダを作成しました。そのなかに、welcome.htmlという名称のファイルを作ります。

/templates/welcome.html

<html>
  <head><title>金星翻車魚(キンボシマンボウ)</title></head>
<body>
ようこそ
</body>
</html>

さらに、このファイルを呼び出すようにwelcome.pyの方を修正。

/welcome.py

import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

class Welcome(webapp.RequestHandler):
    def get(self):
        self.response.out.write(
            template.render(
                os.path.join(os.path.dirname(__file__),
                             'templates',
                             'welcome.html'),
                None)
            )

これで、表示(HTML)とロジック(Python)を分離できました。