webappを使ってフォームを制御する

Handling Forms With webapp

import cgi
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import webapp

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>')

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

if __name__ == "__main__":
 main()

今までは

webapp.WSGIApplication([('/', MainPage)],debug=True)

今回は

webapp.WSGIApplication([('/', MainPage),('/sign', Guestbook)],debug=True)

となっており、太字の部分が追加されている。
この記述により、Guestbookを'/sign'にマップすることができる。
フォームのactionに/signが指定されていることで、メッセージを入力してsubmitすると/signにMainPageの内容がGuestbookにpostされる。

postされた内容を

def post(self):

で受け取り処理している。
このように、webappからフォームをハンドリング(操作)することが可能。

import cgiについて

cgiモジュールはPythonの標準ライブラリの1つで、今回のサンプルでもGuestbookのpostで使われている。

self.response.out.write(cgi.escape(self.request.get('content')))

HTMLで処理されてしまう特殊文字エスケープする。
左がサンプルを実行した時、右がescape記述が無い場合の結果です。