• 検索結果がありません。

第 9 章 アプリケーションのデプロイ 49

10.2 Web ページを追加する

webapp2の役割

call MainHandlerの部分は、MainHandlerをリクエストハンドラとして定義し,ルートのURL ( / )に対応づけて います。webapp2がURL /に対するHTTP GETリクエストを受け取ったとき,MainPageクラスをインスタンス 化してインスタンスのgetメソッドを呼びます。メソッドの中では,リクエストに関する情報がself.requestを通 して知ることができます。

通常,このメソッドはレスポンスの準備をするself.responseにプロパティを設定して終了します。webapp2は

MainPageインスタンスの最終状態に基づいてレスポンスを送信します。

アプリケーション自身はwebapp2.WSGIApplicationインスタンスで表現されます。そのコンストラクタに渡され るパラメータdebug=trueはハンドラにエラーが発生したかキャッチされない例外が発生した場合,webapp2にブ ラウザ出力へのスタックトレースの発行を指示します。

webapp2の役割

call MainHandlerの部分は、MainHandlerをリクエストハンドラとして定義し,ルートのURL ( / )に対応づけて います。webapp2がURL /に対するHTTP GETリクエストを受け取ったとき,MainPageクラスをインスタンス 化してインスタンスのgetメソッドを呼びます。メソッドの中では,リクエストに関する情報がself.requestを通 して知ることができます。

通常,このメソッドはレスポンスの準備をするself.responseにプロパティを設定して終了します。webapp2は

MainPageインスタンスの最終状態に基づいてレスポンスを送信します。

アプリケーション自身はwebapp2.WSGIApplicationインスタンスで表現されます。そのコンストラクタに渡され るパラメータdebug=trueはハンドラにエラーが発生したかキャッチされない例外が発生した場合,webapp2にブ ラウザ出力へのスタックトレースの発行を指示します。

10.2 Web ページを追加する

webappフレームワークの仕組みを使って、Webページの追加の下かについて説明します。

10.2.1 Web ページの追加方法

Webページを追加するには、大きく次の2つの処理が必要です。

ひとつは、リクエストハンドラの作成では、URLに対応するリクエストを処理するリクエストハンドラクラスを 作成します。もうひとつは、URLに対応するリクエストハンドラを呼び出すルート設定です。

リクエストハンドラの作成

URLに対応するリクエストハンドラを作成方法を見てみましょう。ここでは、/mypageにGETでアクセスした 時にHello MyPage!と表示する処理を実装例にします。

• RequestHandlerクラス

– webapp2.RequestHandlerを継承した、独自のRequestHandlerクラスを作成します。

– メソッドの作成

* HTTPのメソッドに対応するメソッドを作成します。GETメソッドの場合は、get。POSTメソッ ドの場合はpostという名前のメソッドを作成します。

1 class MainHandler(webapp2.RequestHandler):

2 def get(self):

3 self.response.write('Hello world!')

5410Webページの追加

4 5

6 class MyPageHandler(webapp2.RequestHandler):

7 def get(self):

8 self.response.write('Hello MyPage!')

ルートの設定

URLに対応するリクエストハンドラの呼び出しを設定します。

• WSGIApplication

– webapp2.WSGIApplicationメソッドの引数に、URLと対応するリクエストハンドラをタプルの配列を 指定します。

デフォルトでは(‘/’, MainHandler)と記述されているので、URL ‘/‘のアクセスがあったときに MainHandlerを呼び出しています。

1 app = webapp2.WSGIApplication([

2 ('/', MainHandler)

3 ], debug=True)

• /mypageに対応するリクエストハンドラを追加します。

– ( /mypage , MyPageHandler )と記述し、/mypageのアクセスがあったときにMyPageHandlerを呼び 出すようにします。

‘ (‘/’, MainHandler)‘のあとに,を追加するのを忘れないようにしてください。

1 app = webapp2.WSGIApplication([

2 ('/', MainHandler), # 行末に , を追加する

3 ( |new-page| , MyPageHandler )

4 ], debug=True)

main.py

main.pyは次のような内容になります。

1 #!/usr/bin/env python

2 #

3 # Copyright 2007 Google Inc.

4 #

5 # Licensed under the Apache License, Version 2.0 (the "License");

6 # you may not use this file except in compliance with the License.

7 # You may obtain a copy of the License at

8 #

10.2. Webページを追加する 55

9 # http://www.apache.org/licenses/LICENSE-2.0

10 #

11 # Unless required by applicable law or agreed to in writing, software

12 # distributed under the License is distributed on an "AS IS" BASIS,

13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

14 # See the License for the specific language governing permissions and

15 # limitations under the License.

16 #

17 import webapp2

18

19 class MainHandler(webapp2.RequestHandler):

20 def get(self):

21 self.response.write('Hello world!')

22

23 class MyPageHandler(webapp2.RequestHandler):

24 def get(self):

25 self.response.write('Hello MyPage!')

26 27

28 app = webapp2.WSGIApplication([

29 ('/', MainHandler),

30 ('/mypage', MyPageHandler)

31 ], debug=True)

確認

http://localhost:8080/maypageにアクセスし、次のように表示されていることを確認します。

10.2.2 実習 1. Web ページを追加する

Hello Worldに新しいURLを追加し、/mypageに対応するリクエストハンドラを作成します。

10.2.3 確認

/mypageにアクセスし、正常に表示されることを確認する。

10.2.4 解答

解答ドキュメントを参照してください。

5610Webページの追加

9 # http://www.apache.org/licenses/LICENSE-2.0

10 #

11 # Unless required by applicable law or agreed to in writing, software

12 # distributed under the License is distributed on an "AS IS" BASIS,

13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

14 # See the License for the specific language governing permissions and

15 # limitations under the License.

16 #

17 import webapp2

18

19 class MainHandler(webapp2.RequestHandler):

20 def get(self):

21 self.response.write('Hello world!')

22

23 class MyPageHandler(webapp2.RequestHandler):

24 def get(self):

25 self.response.write('Hello MyPage!')

26 27

28 app = webapp2.WSGIApplication([

29 ('/', MainHandler),

30 ('/mypage', MyPageHandler)

31 ], debug=True)

確認

http://localhost:8080/maypageにアクセスし、次のように表示されていることを確認します。

10.2.2 実習 1. Web ページを追加する

Hello Worldに新しいURLを追加し、/mypageに対応するリクエストハンドラを作成します。

10.2.3 確認

/mypageにアクセスし、正常に表示されることを確認する。

10.2.4 解答

解答ドキュメントを参照してください。

5610Webページの追加

10.3.1 エラーハンドリングの仕方

webapp2では、エラーのハンドリングが用意されています。次のコードは、404エラーをハンドリングしてい

ます。

1 def handle_404(request, response, exception):

2 logging.exception(exception)

3 response.write('Oops! I could swear this page was here!')

4 response.set_status(404)

5

6 app = webapp2.WSGIApplication([

7 webapp2.Route(r'/', handler='handlers.HomeHandler', name='home')

8 ])

9 app.error_handlers[404] = handle_404

手順

エラーハンドリングは次のような手順で実装します。

1. エラーハンドリングをするための、ハンドラーオブジェクトを作成する 2. WSGIApplicationオブジェクトにエラーメソッドを登録する

手順1. エラーハンドリングをするための、メソッドを作成する

エラー処理をするためのエラーハンドラクラスを作成します。ここでは、404エラーの処理を行うためのメソッド

handle_404を作成しています。resuponnseオブジェクトに、エラーに対応するステータスコードをセットします。

ここでは、404をセットしています。また、ソースの先頭行に

# coding: utf-8

-*-を追加することで、日本語のメッセージを表示することができます。

1 # coding: utf-8

-*-2 # ......

3

4 def handle_404(request, response, exception):

5 response.write('ページが見つかりませんでした。')

6 response.set_status(404)

5810Webページの追加

手順2. WSGIApplicationオブジェクトにエラーメソッドを登録する

WSGIApplicationオブジェクトの、error_handlers配列の、エラーコード番目に対して、ハンドラークラスをセッ トします。

1 app = webapp2.WSGIApplication([

2 webapp2.Route('/', handler='handlers.HomeHandler', name='home')

3 ])

4 app.error_handlers[404] = handle_404

main.py

main.pyは次のような内容になります。

1 # coding: utf-8

-*-2 #!/usr/bin/env python

3 #

4 # Copyright 2007 Google Inc.

5 #

6 # Licensed under the Apache License, Version 2.0 (the "License");

7 # you may not use this file except in compliance with the License.

8 # You may obtain a copy of the License at

9 #

10 # http://www.apache.org/licenses/LICENSE-2.0

11 #

12 # Unless required by applicable law or agreed to in writing, software

13 # distributed under the License is distributed on an "AS IS" BASIS,

14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

15 # See the License for the specific language governing permissions and

16 # limitations under the License.

17 #

18 import webapp2

19 20

21 class MainHandler(webapp2.RequestHandler):

22 def get(self):

23 self.response.write('Hello world!')

24 25

26 class MyPageHandler(webapp2.RequestHandler):

27 def get(self):

28 self.response.write('Hello MyPage!')

29 30

31 def handle_404(request, response, exception):

32 response.write('ページが見つかりませんでした。')