使用 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 要求。

產生通訊協定緩衝區程式庫

如要使用 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

PROJECT = "PROJECT_ID"
REGION = "REGION"
API_ENDPOINT = f"universalledger.{REGION}.rep.googleapis.com"
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

後續步驟