爬虫類嫌いのPython日記

爬虫類が大の苦手の筆者が、Pythonに挑戦。他にも、RubyやObjective-C、Google Appengine、Herokuなど色々とチャレンジしています。

GoogleAppEngineでテンプレートを利用する

GAEでは、Djangoによるテンプレート機能を利用する事が出来ます。
Djangoとは、Pythonでは有名なWebアプリケーションフレームワークです。

HTMLの作成

テンプレートファイルは、プロジェクトフォルダの中にフォルダを作成して、そこに配置します。
ここでは、「Templates」フォルダを作成したと言う前提で説明を進めます。

templates/index.thml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Sample Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="/css/style.css" />
  </head>
  <body>
    <h1>Sample Page</h1>
    <p>HogeHoge</p>
  </body>
</html>

CSSの作成

CSSファイルもプロジェクトフォルダの中にフォルダを作成して配置します。
ここでは、一般的な「css」と言う名前のフォルダを作成し「style.css」を作成します。

css/style.css

body {
    background : #FFFFEE;
    color      : #666633;
    margin     : 0;
}

h1 {
    background : #6699AA;
    color      : #CCFFFF;
    margin     : 0px;
    padding    : 5px;
    font-size  : 16pt;
}

p {
    color     : #336699;
    font-size : 12pt;
    margin    : 10px;
}

app.yamlの修正

app.yamlでは、handlersと言う項目にURLと実行するスクリプトの関係を記述していました。
同様に、CSSディレクトリへのアクセスを例外扱いするように記述します。

app.yamlへの修正分

handlers:
- url: /css
  static_dir: css
  
- url: */
  script: main.py

新たに「- url: /css」として「static_dir: css」と追記しています。
これで、cssディレクトリへのアクセスは、そのまま行われる事になります。
注意する点は、「- url: */」を最後に記述すると言う事です。
最初に記述すると、全てのアクセスに対して「- url: */」が適用されるからです。

main.pyの修正

main.py

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


class MainHandler(webapp.RequestHandler):

  def get(self):
    fpath = os.path.join(os.path.dirname(__file__), 'templates', 'index.html')

    html = template.render(fpath, None)
    self.response.out.write(html)

新たに「os」と「google.appengine.ext.webapp」にある「template」モジュールをインポートしています。
osは、ファイルパスに関する機能を利用するためのモジュールです。
templateは、テンプレート機能を利用するためのモジュールです。

fpath = os.path.join(os.path.dirname(__file__), 'templates', 'index.html')

os.path.joinは、引数に指定したディレクトリやファイルを1つのパスにまとめて返します。
os.path.dirname(__file__)で、このファイルのディレクトリを取得し、「templates」内の「index.html」へのパスを取得しています。

html = template.render(fpath, None)
self.response.out.write(html)

templateのrenderメソッドは、引数に指定したテンプレートファイルを読み込み、それをレンダリングした結果を返します。
その結果を、self.response.out.writeで出力して完了です。