Google App Engine:ファイルの読み込み

Google App Engine のスタートガイドでは、「静的ファイルの使用」について説明がありますが、これ以外の方法でも、静的ファイルを表示する方法があります。それは、スクリプト内でファイルを読み込んで書き出す方法です。

これには、組み込み関数の open() を使います。
そして、read() を組み合わせれば、ファイル全体の読み込みができます。

"index.html" を読み込んで、表示する例を掲載します。

import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class IndexPage(webapp.RequestHandler):
  def get(self):
    html = open('index.html').read()
    self.response.out.write(html)

application = webapp.WSGIApplication([
                                      ('/index.html', IndexPage),
                                     ], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

なお、外部スタイルシートやイメージファイル、JSファイルなどを利用する場合には、app.yaml 内で次のようにリクエストハンドラにマッピングしておく必要があります。css, img, js というディレクトリにそれぞれ css ファイル、画像ファイル、 JSファイルを置く場合の記述例を示します。

handlers:

- url: /css/(.*)
  static_files: css/\1
  upload: css/(.*)

- url: /img/(.*)
  static_files: img/\1
  upload: img/(.*)

- url: /js/(.*)
  static_files: js/\1
  upload: js/(.*)