GoogleAppEngineでテンプレートと静的ファイル

30分プログラム、その551。GoogleAppEngineでテンプレートと静的ファイルを使おう。

テンプレートを使う

templates/index.htmlに適当なファイルを作って、template.renderを使って表示してやる。
templateモジュールにはたいした機能がないので、djangoモジュールを直接使ったほうがいい気がする。

#!/usr/bin/env python
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import os

class MainHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write(template.render(
        "templates/index.html",{}))

def main():
  application = webapp.WSGIApplication([('/', MainHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()

静的ファイル

テンプレートでページの表示はできたので、あとはCSS

application: skk-sync
version: 1
runtime: python
api_version: 1

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

のように、/cssを静的ディレクトリに割り当てる。
あとはcss/に適当なCSSを置いてやれば以下のように使える。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
  <head>
    <link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" />
    <link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
    <!--[if IE]><link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection" /><![endif]-->
...