GoogleAppEngineでURLマッピング
GoogleAppEngineでHelloWorldCommentsで作成したスクリプトでは、http://localhost:8080/以下のどんなURLにアクセスしてもMainHandlerクラスのgetメソッドの処理が実行されます。
そこで、URLマッピングを追加して、複数の処理を実行できるようにします。
URLマッピングの追加
GAEでURLマッピングをする場合、main関数内のwebapp.WSGIApplicationのインスタンスにURLマッピングのリストを渡して追加します。
このリストは(URL, クラス名)と言った形のタプルを値に持ちます。
webapp.WSGIApplication( [URLマッピングのリスト], debug=真偽値)
第2引数のdebugは、デバッグモードのON/OFFです。
main.pyの修正
修正版main.py
from google.appengine.ext import webapp from google.appengine.ext.webapp import util class MainHandler(webapp.RequestHandler): def get(self): self.response.out.write('Main Page!') class HeloHandler(webapp.RequestHandler): def get(self): self.response.out.write('Hello World!') class ByeHandler(webapp.RequestHandler): def get(self): self.response.out.write('Good Bye!') def main(): application = webapp.WSGIApplication([('/', MainHandler), ('/index', MainHandler), ('/hello', HeloHandler), ('/bye', ByeHandler) ], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
[('/', MainHandler), ('/index', MainHandler), ('/hello', HeloHandler), ('/bye', ByeHandler) ]
この部分で、URLマッピングを行っています。
それぞれ、対応するクラスについては、特に説明は不要かと思います。
実際に、プロジェクトをdev_appserver.pyで実行してみてください。
http;//localhost:8080 http://localhost:8080/hello http://localhost:8080/bye
アクセスに対応して、表示されるテキストが変わります。