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

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

  • 透過標準 HTTP 要求叫用的 HTTP 函式。
  • 事件驅動函式,可用來處理來自 Cloud 基礎架構的事件,例如 Pub/Sub 主題中的訊息,或 Cloud Storage 值區中的變更。

本範例說明如何建立簡單的 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.

    Go to project selector

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

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

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

    Go to project selector

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

  7. Enable the Cloud Functions and Cloud Build APIs.

    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 python312 --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

    使用記錄資訊主頁

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