使用 Python (第 1 代) 建立及部署 HTTP Cloud Run 函式

本指南將逐步說明如何使用 Python 執行階段,編寫 Cloud Run 函式。Cloud Run 函式分為兩種類型:

  • HTTP 函式,可透過標準 HTTP 要求叫用。
  • 事件導向函式,用於處理 Cloud 基礎架構的事件,例如 Pub/Sub 主題的訊息,或 Cloud Storage bucket 的變更。

以下範例說明如何建立簡易 HTTP 函式。

事前準備

  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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. 安裝並初始化 gcloud CLI
  9. 更新並安裝 gcloud 元件:
    gcloud components update
  10. 準備開發環境。

    前往 Python 設定指南

  11. 建立函式

    1. 在本機系統建立函式程式碼的目錄:

      Linux 或 Mac OS X

      mkdir ~/helloworld
      cd ~/helloworld
      

      Windows

      mkdir %HOMEPATH%\helloworld
      cd %HOMEPATH%\helloworld
      
    2. helloworld 目錄中建立 main.py 檔案,並加入以下內容:

      
      import functions_framework
      
      
      from markupsafe import escape
      
      @functions_framework.http
      def hello_http(request):
          """HTTP Cloud Function.
          Args:
              request (flask.Request): The request object.
              <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
          Returns:
              The response text, or any set of values that can be turned into a
              Response object using `make_response`
              <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
          """
          request_json = request.get_json(silent=True)
          request_args = request.args
      
          if request_json and "name" in request_json:
              name = request_json["name"]
          elif request_args and "name" in request_args:
              name = request_args["name"]
          else:
              name = "World"
          return f"Hello {escape(name)}!"
      
      

      此範例函式採用在 HTTP 要求中提供的名稱,並傳回問候語;如未提供名稱,則會傳回「Hello World!」。

    指定依附元件

    Python 中的依附元件是透過 pip 管理,並以稱為 requirements.txt 的中繼資料檔案表示。這個檔案所在的目錄,必須與包含函式程式碼的 main.py 檔案相同。

    您不需要建立 requirements.txt 即可執行此範例;如要新增自己的依附元件,方法如下:

    1. helloworld 目錄中建立 requirements.txt 檔案。

    2. 將函式的依附元件新增至 requirements.txt 檔案,例如:

      # An example requirements file, add your dependencies below
      sampleproject==2.0.0
      

    部署函式

    如要使用 HTTP 觸發條件部署函式,請在 helloworld 目錄中執行下列指令:

    gcloud functions deploy hello_http --no-gen2 --runtime python314 --trigger-http --allow-unauthenticated

    若加入 --allow-unauthenticated 旗標,則無須驗證即可使用函式。如要要求驗證,請省略該旗標。

    測試函式

    1. 函式部署完畢後,請記下 httpsTrigger.url 屬性,或使用下列指令找到該屬性:

      gcloud functions describe hello_http
      

      結果應該會類似這樣:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http
    2. 使用瀏覽器造訪這個網址,應該會看到「Hello World!」訊息。

      請嘗試透過 HTTP 要求傳遞名稱,例如使用下列網址:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME

      您應該會看到「Hello NAME!」訊息。

    查看記錄

    您可以使用 Google Cloud CLI,以及在 Cloud Logging UI 中查看 Cloud Run 函式的記錄。

    使用指令列工具

    如要透過 gcloud CLI 查看函式的記錄,請使用 logs read 指令,再加上函式名稱:

    gcloud functions logs read hello_http

    輸出內容應會如下所示:

    LEVEL  NAME        EXECUTION_ID  TIME_UTC                 LOG
    D      hello_http  pdb5ys2t022n  2019-09-18 23:29:09.791  Function execution started
    D      hello_http  pdb5ys2t022n  2019-09-18 23:29:09.798  Function execution took 7 ms, finished with status code: 200

    使用 Logging 資訊主頁

    您也可以在 Google Cloud 控制台查看 Cloud Run 函式的記錄。