フォームのユーザー入力の処理

Python ゲストブック コード チュートリアルのこの部分では、ユーザー入力の処理方法を説明します。

このページは複数ページからなるチュートリアルの一部です。設定などの手順を最初から見るには、ゲストブックの作成に移動してください。

webapp2 を使用するようにアプリを構成する

ゲストブックのサンプルでは、webapp2 フレームワークを使用します。このフレームワークは、App Engine 環境と App Engine Python SDK に含まれています。webapp2 は、アプリケーション コードにバンドルしなくても使用できます。

app.yaml ファイルでは、アプリが webapp2 フレームワークを使用することを指定します。

libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest

webapp2 アプリケーションは 2 つの部分で構成されています。

  • 1 つ以上の RequestHandler クラス。リクエストを処理し、レスポンスを構築します。
  • WSGIApplication インスタンス。受信リクエストを URL に基づいてハンドラに転送します。

app.yaml ファイルでは、すべての URL のハンドラとして guestbook.pyapp オブジェクトを指定します。

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: /bootstrap
  static_dir: bootstrap

- url: /.*
  script: guestbook.app

フォーム送信のハンドラを定義する

guestbook.pyapp オブジェクトは、特定の URL のリクエストを処理するスクリプトが定義された WSGIApplication です。

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

debug=True パラメータにより、ハンドラがエラーを検出するか予期しない例外が発生した場合に、webapp2 がスタック トレースをブラウザに出力します。このオプションは、アプリケーションの最終バージョンをデプロイする前に削除する必要があります。削除しないと、アプリケーションの内部が外部に公開されてしまいます。

Guestbook ハンドラのメソッドは、get() ではなく post() メソッドです。MainPage が表示するフォームは、フォームデータの送信に HTTP POST メソッドを使用するためです。

class Guestbook(webapp2.RequestHandler):

    def post(self):
        # We set the same parent key on the 'Greeting' to ensure each
        # Greeting is in the same entity group. Queries across the
        # single entity group will be consistent. However, the write
        # rate to a single entity group should be limited to
        # ~1/second.
        guestbook_name = self.request.get('guestbook_name',
                                          DEFAULT_GUESTBOOK_NAME)
        greeting = Greeting(parent=guestbook_key(guestbook_name))

        if users.get_current_user():
            greeting.author = Author(
                    identity=users.get_current_user().user_id(),
                    email=users.get_current_user().email())

        greeting.content = self.request.get('content')
        greeting.put()

        query_params = {'guestbook_name': guestbook_name}
        self.redirect('/?' + urllib.urlencode(query_params))

post() メソッドは、self.request からフォームデータを取得します。