為 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.1.3; python_version >= '3.9'
    

測試網路服務

請在本機的虛擬環境中執行網路服務,藉此進行測試:

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: python314

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。