在 App Engine 彈性環境中建立 Python 應用程式

區域 ID

REGION_ID 是 Google 根據您在建立應用程式時選取的地區所指派的簡寫代碼。雖然某些區域 ID 可能看起來與常用的國家/地區代碼相似,但此代碼並非對應國家/地區或省份。如果是 2020 年 2 月後建立的應用程式,App Engine 網址會包含 REGION_ID.r。如果是在此日期之前建立的現有應用程式,網址中則可選擇加入地區 ID。

進一步瞭解區域 ID

本快速入門導覽課程將說明如何建立及部署顯示簡短訊息的應用程式。您可以在 app.yaml 檔案中指定執行階段版本和作業系統,以便針對任何支援的 Python 版本使用本快速入門導覽課程中的範例應用程式。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Build API.

    Enable the API

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  9. Make sure that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Build API.

    Enable the API

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. 由於新專案中 Cloud Build 使用服務帳戶的預設行為有所變更,以及預設安全的機構政策變更,因此您可能需要為部署服務帳戶授予其他角色。如要進一步瞭解如何授予特定角色,請參閱疑難排解指南
  15. 其他必要條件

    1. 使用您的專案將 App Engine 應用程式初始化,然後選擇地區:

      gcloud app create --project=[YOUR_PROJECT_ID]
      

      收到系統提示時,選取 App Engine 應用程式的存放地區

    2. 在本機電腦上安裝下列項目:

  • 執行下列指令來安裝包含 Python 專用 App Engine 擴充功能的 gcloud 元件

    gcloud components install app-engine-python
    

  • 設定 Python 開發環境。建議您在系統中安裝最新版本的 Python、pip 和其他相關工具。如需操作說明,請參閱 Python 開發環境設定指南

  • App Engine 位置

    App Engine 具有「地區性」,這表示執行應用程式的基礎架構位於特定地區,且由 Google 代管,可為該地區內的所有區域提供備援功能。

    選擇應用程式的執行地區時,請將您在延遲時間、可用性和耐用性方面的要求,做為主要考量。一般來說,您可以選擇距離您應用程式使用者最近的地區,但也應該考量App Engine 可用地區,以及應用程式使用的其他Google Cloud 產品和服務位置。如果跨多個位置使用服務,可能會影響應用程式的延遲時間和定價

    應用程式的地區設定完成後即無法更改。

    如果您已建立 App Engine 應用程式,即可執行下列任一操作來查看所在地區:

    本快速入門導覽課程將示範最新的 Python 3 應用程式,該應用程式是使用 Flask 網路架構編寫,可部署到 App Engine。雖然本範例使用 Flask,但您也可利用其他符合上述需求的網路架構。其他的架構包括 DjangoPyramidBottleweb.py

    下載 Hello World 應用程式

    我們建立了 App Engine 適用的 Hello World 應用程式,方便您快速瞭解在 Google Cloud部署應用程式的操作步驟。

    1. 將 Hello World 範例應用程式存放區複製到本機電腦。

      git clone https://github.com/GoogleCloudPlatform/python-docs-samples
      

      您也可以下載 zip 格式的範例,然後解壓縮該檔案。

    2. 變更為包含範例程式碼的目錄。

         cd python-docs-samples/appengine/flexible/hello_world
      

    在本機電腦上執行 Hello World

    在本機電腦上執行 Hello World 應用程式:

    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

      如果您使用 Cloud Shell,請在工具列中按一下「Web Preview」(網頁預覽) 圖示 ,然後選取「透過以下通訊埠預覽: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

    此時頁面會顯示來自範例應用程式的 Hello World 訊息。請在終端機視窗中,按下 Ctrl+C 鍵來關閉網路伺服器。

    在 App Engine 上部署並執行 Hello World

    如要將您的應用程式部署到 App Engine 彈性環境:

    1. hello_world 目錄執行下列指令,以部署 Hello World 應用程式:

      gcloud app deploy

      瞭解選用標記

      常見的 gcloud 指令標記

      • 加上 --version 標記以指定專門用來辨識您應用程式版本的 ID。如未指定,將由系統自動產生,例如:--version [YOUR_VERSION_ID]
      • 加上 --project 標記以指定替代 Google Cloud 專案 ID,而不使用您在 gcloud 工具中初始化為預設值的 ID。示例: --project [YOUR_PROJECT_ID]

      範例:

      gcloud app deploy --version pre-prod-5 --project my-sample-app

      如要進一步瞭解如何透過指令列部署應用程式,請參閱測試及部署您的應用程式。如需所有指令標記的清單,請參閱 gcloud app deploy 參考資料。

    2. 啟動瀏覽器,並前往 https://PROJECT_ID.REGION_ID.r.appspot.com 查看應用程式

      gcloud app browse
      ,其中 PROJECT_ID 代表您的 Google Cloud專案 ID。

    此時,顯示 Hello World 訊息的頁面是由在 App Engine 執行個體上運作的網路伺服器提供。

    恭喜!您已將第一個 App Engine 應用程式部署至 App Engine 彈性環境!

    如果在部署應用程式時遇到任何錯誤,請參閱疑難排解提示

    請參閱下列各節,瞭解清除所用資源的資訊,並取得相關後續步驟的連結。

    清除所用資源

    如要避免產生費用,您可以刪除 Google Cloud 專案,這樣系統就會停止對專案中使用的所有資源計費。

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    後續步驟

    瞭解整個平台

    現在您已瞭解如何開發及部署 App Engine 應用程式,接著可以探索 Google Cloud的其他部分。您已安裝 Google Cloud CLI,因此擁有能與 Cloud SQL、Cloud Storage、Firestore 等產品互動的工具。

    瞭解 App Engine 彈性環境

    以下是一些可協助您瞭解 App Engine 的主題:

    Hello World 程式碼審查

    Hello World 是再簡單不過的 App Engine 應用程式,只包含一項服務、只有一種版本,且所有程式碼都位於應用程式的根目錄中。本節將詳細說明每個應用程式檔案。

    main.py

    Hello World 是基本的單一檔案 Flask 應用程式。

    from flask import Flask
    
    
    app = Flask(__name__)
    
    
    @app.route("/")
    def hello() -> str:
        """Return a friendly HTTP greeting.
    
        Returns:
            A string with the words 'Hello World!'.
        """
        return "Hello World!"
    
    
    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.
        app.run(host="127.0.0.1", port=8080, debug=True)

    app.yaml

    app.yaml 檔案說明應用程式的下列設定:

    • 設定 env: flex,表示應用程式使用 App Engine 彈性環境
    • 指定應用程式使用的執行階段。如果您不使用 runtime_version 設定,App Engine 會使用最新的 Python 版本做為應用程式的預設版本。

    • entrypoint 會告訴 App Engine 如何啟動應用程式。此應用程式會使用 gunicorn 提供 Python 應用程式,做為 Flask 開發伺服器的替代方案 (在本機執行時使用)。App Engine 啟動應用程式時會設定 $PORT 變數。如要進一步瞭解 entrypoint,請參閱「啟動應用程式」一節。

    # 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: python
    env: flex
    entrypoint: gunicorn -b :$PORT main:app
    
    runtime_config:
      operating_system: ubuntu22
    
    # This sample incurs costs to run on the App Engine flexible environment.
    # The settings below are to reduce costs during testing and are not appropriate
    # for production use. For more information, see:
    # https://cloud.google.com/appengine/docs/flexible/python/configuring-your-app-with-app-yaml
    manual_scaling:
      instances: 1
    resources:
      cpu: 1
      memory_gb: 0.5
      disk_size_gb: 10
    

    requirements.txt

    requirements.txt 和 Python 套件管理工具 pip 會宣告及安裝應用程式依附元件。Hello World 需要網路架構 Flask 和 WSGI 伺服器 Gunicorn

    Flask==3.0.3; python_version > '3.6'
    Flask==2.3.3; python_version < '3.7'
    Werkzeug==3.0.3; python_version > '3.6'
    Werkzeug==2.3.8; python_version < '3.7'
    gunicorn==23.0.0

    requirements.txt 用於定義程式庫;該程式庫將安裝於本機,也會在部署至 App Engine 時一併安裝。