使用 Python 傳送 RPC 要求

應用程式可以使用 gRPC 和 Python 與 Universal Ledger API 互動。這種做法需要產生並使用從服務的通訊協定緩衝區定義編譯的 Python 用戶端程式庫。

本教學課程適用於想為 Universal Ledger API 實作用戶端的開發人員,說明如何設定合適的開發環境、產生必要程式庫,以及使用 Python 進行 gRPC 呼叫。

事前準備

如要完成本教學課程,您需要:

  • 啟用 Universal Ledger API 的 Google Cloud 專案。

  • IAM 角色,例如 universalledger.googleapis.com/endpointViewer,這樣您至少可以查看 Universal Ledger 端點。

  • 使用者帳戶的本機驗證憑證。執行下列指令來設定這些憑證:

    gcloud auth application-default login

如要進一步瞭解這些步驟,請參閱私人搶先體驗計畫新手上路指南。

設定環境

本教學課程中的操作說明適用於執行 Ubuntu 25.04 的環境,其中預設包含 Python 3.13。如果您使用其他作業系統,可能需要修改指令。

如要設定開發環境,請完成下列步驟。這些步驟會引導您安裝必要的指令列工具。包括使用 pipx 安裝 grpcio-tools,後者用於建構 gRPC 繫結。如要隔離這個專案的 Python 依附元件,您也需要建立並啟動 Python 虛擬環境,然後使用 pip 將必要的 Python 程式庫安裝到該環境中。

  1. 使用下列指令安裝基本依附元件:

    sudo apt update
    sudo apt install git pipx python3.13-venv
  2. 使用 pipx 安裝 gRPC 工具應用程式,並確保其二進位目錄已新增至 PATH

    pipx install grpcio-tools
    pipx ensurepath

    關閉並重新開啟終端機,完成 pipx 的啟用程序。

  3. 建立上層目錄,用來存放本教學課程的檔案。

    mkdir gcul_tutorial
    cd gcul_tutorial

    除非另有指定,否則其餘指令應從這個新目錄內執行。

  4. 建立 Python 虛擬環境,並安裝其餘程式庫:

    python3 -m venv example_client
    cd example_client
    source ./bin/activate
    pip3 install google-auth googleapis-common-protos grpcio requests
    cd ..

    這些程式庫包括:

    • google-auth:用於處理驗證。 Google Cloud
    • googleapis-common-protos:Google API 中使用的常見通訊協定緩衝區訊息。
    • grpcio:適用於 Python 的 gRPC 程式庫。
    • requests:部分依附元件需要此項目才能傳送 HTTP 要求。

產生 Protocol Buffer 程式庫

如要使用 gRPC 與 Universal Ledger API 互動,Python 應用程式需要從服務的通訊協定緩衝區 (.proto) 定義編譯的用戶端程式庫。這些定義會指定 API 的服務、方法和訊息類型。

本節說明如何從 googleapis 存放區下載這些 .proto 檔案,並使用已安裝的 grpcio-tools 生成必要的 Python 原始碼。

  1. 複製 googleapis GitHub 存放區,其中發布了 Google API 的通訊協定緩衝區定義。

    git clone https://github.com/googleapis/googleapis.git
  2. 為 Universal Ledger API 建構通訊協定緩衝區定義和 gRPC 繫結。

    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        --grpc_python_out=example_client \
        google/cloud/universalledger/v1/universalledger.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/query.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/accounts.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/common.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/transactions.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/types.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/status_event.proto

    這樣應該會在 example_client/google/cloud/universalledger/v1 目錄下建立多個檔案。

    accounts_pb2.py
    accounts_pb2.pyi
    common_pb2.py
    common_pb2.pyi
    query_pb2.py
    query_pb2.pyi
    status_event_pb2.py
    status_event_pb2.pyi
    transactions_pb2.py
    transactions_pb2.pyi
    types_pb2.py
    types_pb2.pyi
    universalledger_pb2.py
    universalledger_pb2.pyi
    universalledger_pb2_grpc.py
    

呼叫 Universal Ledger API

最後,請建立 Python 指令碼,使用產生的程式庫呼叫 Universal Ledger API。將下列程式碼儲存為 example_client/endpoints.py

在程式碼中,替換下列預留位置值:

  • PROJECT_ID:您的 Google Cloud 專案 ID,例如 my-project
  • REGION:Universal Ledger 端點所在的 Google Cloud 區域,例如 us-east5
"""Example calling the Universal Ledger API."""

import sys

import google.auth
import google.auth.transport.grpc
import google.auth.transport.requests
from google.cloud.universalledger.v1 import universalledger_pb2
from google.cloud.universalledger.v1 import universalledger_pb2_grpc
import grpc

API_ENDPOINT = "universalledger.googleapis.com"
PROJECT = "PROJECT_ID"
REGION = "REGION"
SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]


def main() -> str | None:
  # Get the application default credentials.
  credentials, _ = google.auth.default(scopes=SCOPES)

  # Get an HTTP request function to refresh credentials.
  refresh_request = google.auth.transport.requests.Request()

  # Create a secure channel to the API endpoint.
  with google.auth.transport.grpc.secure_authorized_channel(
      credentials, refresh_request, API_ENDPOINT
  ) as channel:
    # Create the client stub using the generated code.
    stub = universalledger_pb2_grpc.UniversalLedgerStub(channel)

    # Parent location for GCUL network endpoints.
    parent = f"projects/{PROJECT}/locations/{REGION}"

    # Build the request message.
    request = universalledger_pb2.ListEndpointsRequest(parent=parent)

    # Make the gRPC call.
    try:
      metadata = [("x-goog-request-params", f"parent={parent}")]
      response = stub.ListEndpoints(request, metadata=metadata)
    except grpc.RpcError as exc:
      return f"{exc.code().name}: {exc.details()}"

    if not response.endpoints:
      return f"No endpoints found under: {parent}"

    print("Found the following endpoints:")
    for endpoint in response.endpoints:
      print("-", endpoint.name)


if __name__ == "__main__":
  sys.exit(main())

如要執行指令碼,請前往 example_client 目錄。虛擬環境應仍處於啟用狀態 (在設定步驟中啟用)。

  1. 切換至指令碼目錄:

    cd example_client
    

    殼層提示應會確認虛擬環境已啟動 (例如,提示會包含 (example_client) 前置字元)。

  2. 執行 Python 指令碼:

    python3 endpoints.py
    

畫面會顯示類似以下的輸出:

Found the following endpoints:
- projects/my-project/locations/us-east5/endpoint/gcul-pilot-testing
- projects/my-project/locations/us-east5/endpoint/gcul-user-testing

後續步驟