使用 Python 建立及部署 HTTP Cloud Run 函式 (第 1 代)
本指南將逐步說明如何使用 Python 執行階段編寫 Cloud Run 函式。Cloud Run 函式分為兩種類型:
- HTTP 函式,可從標準 HTTP 要求叫用。
- 事件驅動函式,用於處理 Cloud 基礎架構中的事件,例如 Pub/Sub 主題上的訊息,或 Cloud Storage 值區中的變更。
這個範例說明如何建立簡單的 HTTP 函式。
事前準備
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
- 安裝並初始化 gcloud CLI。
- 更新並安裝
gcloud
元件:gcloud components update
- 準備開發環境。
在本機系統上為函式程式碼建立目錄:
Linux 或 Mac OS X
mkdir ~/helloworld cd ~/helloworld
Windows
mkdir %HOMEPATH%\helloworld cd %HOMEPATH%\helloworld
在
helloworld
目錄中建立main.py
檔案,並加入以下內容:此範例函式採用在 HTTP 要求中提供的名稱,並傳回問候語,如未提供任何名稱,系統會傳回「Hello World!」。
在
helloworld
目錄中建立requirements.txt
檔案。將函式的依附元件新增至
requirements.txt
檔案,例如:# An example requirements file, add your dependencies below sampleproject==2.0.0
函式完成部署後,請記下
httpsTrigger.url
屬性,或使用下列指令找到這個屬性:gcloud functions describe hello_http
內容應該會類似這樣:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http
透過您的瀏覽器造訪這個網址。您應該會看到「Hello World!」訊息。
請嘗試透過 HTTP 要求傳送名稱,例如使用下列網址:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME
您應該會看到「Hello
NAME
!」訊息
建立函式
指定依附元件
Python 中的依附元件是透過 pip 管理,並以稱為 requirements.txt
的中繼資料檔案表示。這個檔案必須與包含函式程式碼的 main.py
檔案位在同一目錄。
您不需要建立 requirements.txt
即可執行這個特定範例,但假設您想新增自己的依附元件,方法如下:
部署函式
如要使用 HTTP 觸發條件部署函式,請在 helloworld
目錄中執行下列指令:
gcloud functions deploy hello_http --no-gen2 --runtime python312 --trigger-http --allow-unauthenticated
--allow-unauthenticated
旗標可讓您不必驗證就能使用函式。如要要求驗證,請略過該旗標。
測試函式
查看記錄
您可以使用 Google Cloud CLI,以及在 Cloud Logging UI 中查看 Cloud Run functions 的記錄。
使用指令列工具
如要透過 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 functions 的記錄。