為 App Engine 編寫基本網路服務

使用 Flask 編寫並在本機測試提供靜態 HTML 檔案的網路服務。接著,請建立將網路服務部署至 App Engine 所需的設定檔。

在這個步驟中,您會建立一個網路服務版本來顯示預留位置資料,並對此版本進行本機測試。這裡的目標是確保基本網路服務正常運作,再新增 Datastore 和 Firebase 驗證。

事前準備

  1. 如果您尚未建立 Google Cloud 專案,請建立 Google Cloud 專案

  2. 如果您尚未設定 Python 3 部署作業的本機環境,請執行下列步驟:

    • 下載並安裝 Python 3,部署網路服務並執行 Google Cloud CLI。

    • 使用您的 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.jsstatic/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

視窗

請使用 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,請在專案的根目錄中建立 app.yaml 檔案,例如 building-an-app

# 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: python313

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。