Amazon

2011年8月7日日曜日

Google App Engineでケータイサイトを作る際のポイント


参考:Google App Engineで、携帯サイトをつくる


○シフトJISのページを表示するには?

  1.  シフトJISで書いたテンプレートを使います(サンプルではtemplate_mobile.html)
  2.  self.response.headersを使って、ヘッダーにシフトJISである旨、情報を追加します
  3.  カスタムフィルター(サンプルではcustomfilters_m.py)を使って、テンプレートに差し込む文字列をユニコードからシフトJISに変換します

○シフトJISのページからPOSTされたデータを受け取るには?
  1.     POSTされたデータを受け取るためにself.request.get()を使っても、その結果はすでに文字化けしています
  2.     self.request.get()を使うまえに、self.request.charsetを定義します

○"~","-", "‐", "||"などの変換
上記の方法で body.encode('Shift-JIS')で変換しても以下のエラーが出る場合がある
UnicodeEncodeError: 'shift_jis' codec can't encode character u'\uff5e'
どうやらMSとUnicodeとShift-JISの間での変換マッピングにズレがあるようで、これを直す必要がある。

[参考]Pythonで「~」をエンコードすると例外が発生


サンプルコード
mobile.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import wsgiref.handlers, os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

webapp.template.register_template_library('customfilters_m')

class MainPage(webapp.RequestHandler):
    def get(self):
        message = u"ようこそ、テストのサイトへ"
        template_values = {
            'message': message,
        }
        path = os.path.join(os.path.dirname(__file__), "template_mobile.html")
        self.response.headers['Content-Type'] = "text/html; charset=Shift_JIS"
        self.response.out.write(template.render(path, template_values))
    def post(self):
        self.request.charset = "Shift_JIS"
        message = self.request.get("new_message")        
        template_values = {
            'message': message,
        }
        path = os.path.join(os.path.dirname(__file__), "template_mobile.html")
        self.response.headers['Content-Type'] = "text/html; charset=Shift_JIS"
        self.response.out.write(template.render(path, template_values))

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

if __name__ == "__main__":
    main()
customfilters_m.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import datetime
from google.appengine.ext import webapp

register = webapp.template.create_template_register()

def sjis(body):
body = string.replace(body, u'\uff5e', u'\u301c') # fullwidth tilde "~"
    body = string.replace(body, u'\u2015', u'\u2014') # Horizontal bar "―"
    body = string.replace(body, u'\u2225', u'\u2016') # Parallel to "||"
    body = string.replace(body, u'\uff0d', u'\u2212') # Fullwidth hyphen-minus "-"
    return body.encode('Shift_JIS')

register.filter(sjis)
template_mobile.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=SHIFT_JIS" />
<title>テスト</title>
</head>
<body>
{{ message|sjis }}
<form method="post" action="#">
<input type="text" name="new_message" /><br>
<input type="submit" value="送信"  />
</form>
</body>
</html>


○モデルに日本時刻で記録するには?
Google App Engineで以下のようにモデルをつくっておくと、データが挿入されたときに、自動的にその時の時刻が記録されていくので便利なのだが、この時刻はUTCであって日本時間ではない。UTCで記録していくのはよいとして、表示するときは、どうにかして9時間プラスしておかないとまずい。
from google.appengine.ext import db
class hoge(db.Model):
    timestamp = db.DateTimeProperty(auto_now_add=True)
解決方法

テンプレートに、与えられた時刻に9時間を足すカスタムフィルターを登録する。

(1) 以下のコードをcustomfilters.pyというファイル名で保存する。
import datetime
from google.appengine.ext import webapp
register = webapp.template.create_template_register()
def jshift(body):
    return body + datetime.timedelta(hours=9)
register.filter(jshift)
(2) メインとなるコードのほうに以下の1文を追加する。モジュールのインポートが終わったあたりがよい。
webapp.template.register_template_library('customfilters')
(3) テンプレートでは、以下のように記述する。
<p>{{ item.timestamp|jshift|date:"Y-m-d H:i" }}</p>

0 件のコメント:

コメントを投稿

Amazon3