為 App Engine 編寫基本網路服務

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

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

事前準備

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

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

    • 下載並安裝 Python 3,以便開發 Web 服務及執行 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.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 檔案中,設定 Web 服務所需的所有依附元件:

    Flask==3.1.3; python_version >= '3.9'
    

測試網路服務

在本機虛擬環境中執行 Web 服務,藉此測試服務:

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 捷徑上按一下滑鼠右鍵,然後以管理員身分啟動。
  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 的網路服務

如要將 Web 服務部署至 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。