今回は webapp フレームワークを使ったフォームの操作方法を紹介する。ウェブフォームから送信されたメッセージを受け取り、画面に返すという簡単な処理だ。
では早速 helloworld.py を以下のように編集してみよう。
# -*- coding: utf-8 -*-
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<body>
<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>""")
class Guestbook(webapp.RequestHandler):
def post(self):
self.response.out.write('<html><body>You wrote:<pre>')
self.response.out.write(cgi.escape(self.request.get('content')))
self.response.out.write('</pre></body></html>')
application = webapp.WSGIApplication(
[('/', MainPage),
('/sign', Guestbook)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
開発用Webサーバを起動し、http://localhost:8080 へアクセス。
フォームが表示されていることを確認できたら、テキストボックスに何か適当に文字列を打ち込んで、「Sign Guestbook」ボタンを押してデータを送信してみよう。そうすると次の画面で自分が入力したデータが表示されていることだろう。
では、上のソースコードの説明に入る。
まず、以下のコードでURLと処理クラスを紐付けている。
application = webapp.WSGIApplication(
[('/', MainPage),
('/sign', Guestbook)],
debug=True)
/ がブラウザから呼ばれるとMainPageクラスで処理を行い、/sign がブラウザから呼ばれると Gustbook クラスで処理を行うということだ。これは前回説明した通りだから、もうこれ以上の説明は要らないだろう。
そのMainPageクラスでは以下のようにgetメソッド内で初期画面を描画するためのHTMLが出力されている。そのHTMLには form も記述されていて、「Sign Guestbook」ボタンを押すと、textareaで入力したデータを content という名前で /sign というURLへ向けてpostするようになっている。
<form action="/sign" method="post">
そして、/sign と紐付いた Guestbookクラスの post メソッドの処理へと移る。
class Guestbook(webapp.RequestHandler):
def post(self):
self.response.out.write('<html><body>You wrote:<pre>')
self.response.out.write(cgi.escape(self.request.get('content')))
self.response.out.write('</pre></body></html>')
この処理が行っていることは至って単純だ。
self.request.get('content') という処理で先程のフォームから送られてきた content という名称のデータの値を取得し、そのデータを cgi.escape()でHTML特殊文字をエスケープして表示しているだけのことである。
ちなみに、このcgi.escape()のcgiというモジュールは、Pythonの標準ライブラリに含まれるモジュールである。
webapp フレームワークを使ったフォーム操作は以上だ。
webapp は非常にシンプルで理解しやすいフレームワークであることが分かるだろう。
さて、次回はデータストア(GAE用のデータベースみたいなもの)を利用してデータを保存・取得する方法を紹介したいと思う。
(続く)
ここはひとつポチっとよろしく。

プログラミング Google App Engine
posted with amazlet at 11.05.16
Dan Sanderson
オライリージャパン
売り上げランキング: 48590
オライリージャパン
売り上げランキング: 48590