App Engine 用の基本的なウェブサービスの作成

Flask を使用して、静的 HTML ファイルを提供するウェブサービスを作成し、ローカルでテストします。次に、App Engine にウェブサービスをデプロイするために必要な構成ファイルを作成します。

このステップでは、プレースホルダ データを表示できるバージョンのウェブサービスを作成し、ローカルでテストします。Datastore と Firebase Authentication を追加する前に、基本的なウェブサービスが動作していることを確認することが目標になります。

始める前に

  1. Google Cloud プロジェクトをまだ作成していない場合は、Google Cloud プロジェクトを作成します。

  2. Python 3 開発用のローカル環境をまだ設定していなければ、次の手順で設定します。

    • ウェブサービスの開発と Google Cloud CLI の実行用に、Python 3 をダウンロードしてインストールします。

    • Google Cloud ユーザー認証情報を使用して Google Cloud CLI への認証を行い、Datastore でローカルテストを実行できるようにします。

      gcloud auth application-default login
      

ウェブサービス ファイルの構造化

ウェブサービスを作成するプロジェクト ディレクトリは、次のようなファイル構造になります。

  • building-an-app/
    • app.yaml
    • main.py
    • requirements.txt
    • static/
      • script.js
      • style.css
    • templates/
      • index.html

以下のセクションでは、プロジェクト ディレクトリ内にファイルを設定する方法の例を示します。

ウェブサービスの作成

ウェブサービスの初期のイテレーションでは、Flask を使用して Jinja ベースの HTML テンプレートを提供します。

ウェブサービスを設定するには:

  1. templates/index.html ファイルを作成します。

    <!doctype html>
    <!--
     Copyright 2021 Google LLC
    
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
    -->
    
    <html>
    <head>
      <title>Datastore and Firebase Auth Example</title>
      <script src="{{ url_for('static', filename='script.js') }}"></script>
      <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    </head>
    <body>
    
      <h1>Datastore and Firebase Auth Example</h1>
    
      <h2>Last 10 visits</h2>
      {% for time in times %}
        <p>{{ time }}</p>
      {% endfor %}
    
    </body>
    </html>
    
  2. static/script.js および static/style.css ファイルを使用して動作とスタイルを追加します。

    'use strict';
    
    window.addEventListener('load', function () {
    
      console.log("Hello World!");
    
    });
    /**
     * Copyright 2021 Google LLC
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    body {
      font-family: "helvetica", sans-serif;
      text-align: center;
    }
    
  3. main.py ファイルで Flask を使用して、プレースホルダ データで HTML テンプレートをレンダリングします。

    import datetime
    
    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route("/")
    def root():
        # For the sake of example, use static information to inflate the template.
        # This will be replaced with real information in later steps.
        dummy_times = [
            datetime.datetime(2018, 1, 1, 10, 0, 0),
            datetime.datetime(2018, 1, 2, 10, 30, 0),
            datetime.datetime(2018, 1, 3, 11, 0, 0),
        ]
    
        return render_template("index.html", times=dummy_times)
    
    if __name__ == "__main__":
        # This is used when running locally only. When deploying to Google App
        # Engine, a webserver process such as Gunicorn will serve the app. This
        # can be configured by adding an `entrypoint` to app.yaml.
        # Flask's development server will automatically serve static files in
        # the "static" directory. See:
        # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
        # App Engine itself will serve those files as configured in app.yaml.
        app.run(host="127.0.0.1", port=8080, debug=True)
  4. requirements.txt ファイルで、ウェブサービスに必要なすべての依存関係を構成します。

    Flask==3.0.0
    

ウェブサービスのテスト

ウェブサービスを仮想環境でローカルに実行してテストします。

Mac OS / Linux

  1. 分離された Python 環境を作成します。
    python3 -m venv env
    source env/bin/activate
  2. 現在のディレクトリにサンプルコードが含まれていない場合は、hello_world サンプルコードが含まれるディレクトリに移動します。その後、依存関係をインストールします。
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  3. アプリケーションを実行します。
    python main.py
  4. ウェブブラウザに次のアドレスを入力します。
    http://localhost:8080

Windows

PowerShell を使用して Python パッケージを実行します。

  1. インストールされた PowerShell を探します。
  2. PowerShell へのショートカットを右クリックし、管理者として PowerShell を起動します。
  3. 分離された Python 環境を作成します。
    python -m venv env
    .\env\Scripts\activate
  4. プロジェクト ディレクトリに移動し、依存関係をインストールします。現在のディレクトリにサンプルコードが含まれていない場合は、hello_world サンプルコードが含まれるディレクトリに移動します。その後、依存関係をインストールします。
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. アプリケーションを実行します。
    python main.py
  6. ウェブブラウザに次のアドレスを入力します。
    http://localhost:8080

App Engine 用のウェブサービスの構成

ウェブサービスを App Engine にデプロイするには、app.yaml ファイルが必要です。この構成ファイルでは、App Engine 用のウェブサービスの設定を定義します。

ウェブサービスを構成して App Engine にデプロイするには、次のようにプロジェクトのルート ディレクトリ(例: building-an-app)で app.yaml ファイルを作成します。

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: python39

handlers:
  # This configures Google App Engine to serve the files in the app's static
  # directory.
- url: /static
  static_dir: static

  # This handler routes all requests not caught above to your main app. It is
  # required when static routes are defined, but can be omitted (along with
  # the entire handlers section) when there are no static files defined.
- url: /.*
  script: auto

このシンプルなウェブサービスでは、app.yaml ファイルで定義する必要があるのはランタイム設定と静的ファイルのハンドラだけです。

さらに複雑なウェブサービスの場合は、スケーリング、追加のハンドラ、環境変数やサービス名などのアプリケーション要素などの追加設定を app.yaml で構成します。詳細とサポートされている要素すべての一覧については、app.yaml リファレンスをご覧ください。

次のステップ

ウェブサービスの構成、作成、テストが完了したので、次にこのバージョンのウェブサービスを App Engine にデプロイします。