その前にまず、dateutil という便利な外部モジュールをダウンロードしておこう。これは読んで字のごとく日付変換ユーティリティである。
dateutilのインストールは簡単で、解凍したフォルダ内の dateutil フォルダをそのままGAEアプリのプロジェクトフォルダにコピーするだけだ。
dateutilを準備できたら、いよいよサンプルアプリの作成だ。
今回は単純な掲示板アプリをカスタムタグを利用して実装してみる。
まずはカスタムタグ templatefilters.py を実装する。
templatefilters.py
#!-*- coding:utf-8 -*-
# カスタムフィルタ作成に必要
from google.appengine.ext import webapp
import datetime
import dateutil.parser
import dateutil.tz
# レジストリを取得し、最後に自作フィルタを登録する。
register = webapp.template.create_template_register()
# UTC→JST変換フィルタ定義
def jst (value):
return value.replace(tzinfo=dateutil.tz.tzutc()).astimezone(dateutil.tz.gettz('Asia/Tokyo'))
# UTC→JST変換フィルタの登録
register.filter(jst)
次にお馴染みのhelloworld.pyだ。
helloworld.py
# -*- coding: utf-8 -*-
import cgi
import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from datetime import datetime
import dateutil.parser
import logging
# カスタムタグの登録
webapp.template.register_template_library('templatefilters')
class Greeting(db.Model):
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
class MainPage(webapp.RequestHandler):
def get(self):
greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")
template_values = {
'greetings': greetings
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
greeting.content = self.request.get('content')
greeting.date = datetime.now()
greeting.put()
self.redirect('/')
application = webapp.WSGIApplication(
[('/', MainPage),
('/sign', Guestbook)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
上記のコードで大切なのは、カスタムタグ(templatefilters.py)を登録している以下の部分だ。
webapp.template.register_template_library('templatefilters')
ここでちょっと話が逸れる。
日付を文字列で受け取りたい時もあると思う。そんな時のためにdateutilで日付文字列をdatetime型へ変換する方法も紹介しておこうと思う。以下のようにすれば日付文字列のフォーマットから自動的に判断してdatetimeに変換してくれる。
dateutil.parser.parse('2011-06-15T23:55:59+09:00')
さて、気を取りなおして、最後にテンプレートHTMLであるindex.htmlだ。
index.html
<html>
<body>
{% for greeting in greetings %}
<blockquote>
{{ greeting.date|jst|date:"Y-m-d H:i:s" }}
:
{{ greeting.content|escape }}
</blockquote>
{% endfor %}
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
</body>
</html>
上記のコードで大切なのは以下の部分。
{{ greeting.date|jst|date:"Y-m-d H:i:s" }}
UTC な datetime で格納されている greeting.date を先程自作したフィルタのjst関数を通して JST へ変換している。
以上だ。
今回は、GAE/Pでの「カスタムタグの作り方」と「dateutil」の使い方の両方を学習できて一石二鳥のエントリだったね。
ちなみに、SEOとかを気にしないのであれば、JavascriptでJST変換する方法もある。まぁTPOで使い分けるといいだろう。
ここはひとつポチっとよろしく。

プログラミング Google App Engine
posted with amazlet at 11.06.03
Dan Sanderson
オライリージャパン
売り上げランキング: 40082
オライリージャパン
売り上げランキング: 40082
【GAE for Pythonの最新記事】
- GAE/Pでmemcacheを利用してデ..
- PythonでJST日付をUTC(GMT..
- BeautifulSoupオブジェクトを..
- GAE/Pで詳細なエラーログ(トレース情..
- Pythonでオブジェクトのlistをソ..
- GAE/PでAspyctを使ってAOP(..
- GAE/PでBeautifulSoupを..
- GAE/Pでログインが必要なページを取得..
- GAE/Pでファイルアップロード。
- GAE/Pでリクエストデータの扱い方。
- GAE/PでCRONを使ったスケジュール..
- GAE/PでModelをJSON変換する..
- GAE/P向け統合開発環境 Eclips..
- GAE/PとjQueryでJSONデータ..
- GAE+Pythonの標準モジュールだけ..
- GAE+Pythonでテンプレートの共通..
- GAEアプリをアップロードする方法。
- GAE+Pythonでテンプレートエンジ..
- GAE+Pythonでデータストアを操作..
- webappフレームワークを使ったフォー..