Google App Engine でクエリ・ストリングを取得する。
クエリ・ストリング(query string)を取得するには、リクエスト・ハンドラ(request handler)の get()メソッド(method)を利用すればよい。
例えば、http://example.appspot.com/entry=test というリクエストがあった場合、'/'へのリクエストを'MainPage'ハンドラにマッピング(mapping)しておいたとしする。'MainPage'ハンドラのget()メソッドを次のように定義すれば、リクエスト・パラメータ(request parameter)の値を取得できる。
class MainPage(webapp.RequestHandler): def get(self): try: entry = self.request.get('entry') if entry=='': entry='No Entry' except (TypeError, ValueError): entry = 'Error' self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(entry)
何のクエリストリングもない、あるいはクエリストリングに'entry'というパラメータがないときは'No Entry'と表示される。
テストコード
app.yaml
application: netarrows version: 1 runtime: python api_version: 1 handlers: - url: /.* script: getParam.py
getParam.py
from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainPage(webapp.RequestHandler): def get(self): try: entry = self.request.get('entry') if entry=='': entry='No Entry' except (TypeError, ValueError): entry = 'Error' self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(entry) application = webapp.WSGIApplication( [('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
PHPで $_GET['entry']と表現していた部分が、ややこしくなったと考えればいいのだろう。
Javacript だと、location.search で取得した文字列から'?'を取り除き、'&'で分割して、さらに'='でキーと値に分ける処理をする。
慣れれば大丈夫だろう。
参考:
Google App Engine webapp フレームワーク リクエスト ハンドラ
http://code.google.com/intl/ja/appengine/docs/python/tools/webapp/requesthandlers.html