שליחת בקשות RPC באמצעות Python

אפליקציות יכולות לקיים אינטראקציה עם Universal Ledger API באמצעות gRPC ו-Python. בגישה הזו, יוצרים ספריות לקוח ב-Python שמקומפלות מההגדרות של מאגר האחסון לפרוטוקולים של השירות, ומשתמשים בהן.

במדריך הזה נסביר למפתחים שרוצים להטמיע לקוח ל-Universal Ledger API איך להגדיר סביבת פיתוח מתאימה, ליצור את הספריות הנדרשות ולבצע קריאת gRPC באמצעות Python.

לפני שמתחילים

כדי להשלים את המדריך הזה, תצטרכו:

  • פרויקט ב- Google Cloud שבו מופעל Universal Ledger API.

  • תפקיד ב-IAM כמו universalledger.googleapis.com/endpointViewer, כדי שתוכלו לפחות לראות את נקודות הקצה של Universal Ledger.

  • פרטי כניסה לאימות מקומי בחשבון המשתמש. כדי להגדיר את פרטי הכניסה האלה, מריצים את הפקודה הבאה:

    gcloud auth application-default login

מידע נוסף על השלבים האלה זמין במדריך תחילת העבודה.

מגדירים את הסביבה

ההוראות במדריך הזה נכתבו לסביבה שבה פועלת מערכת Ubuntu 25.04, שכוללת את Python 3.13 כברירת מחדל. אם אתם משתמשים במערכת הפעלה אחרת, יכול להיות שתצטרכו לשנות את הפקודות.

כדי להגדיר את סביבת הפיתוח, מבצעים את השלבים הבאים. בשלבים האלה מוסבר איך להתקין את כלי שורת הפקודה הנדרשים. זה כולל שימוש ב-pipx כדי להתקין את grpcio-tools, שמשמש ליצירת קישורי gRPC. כדי לבודד את יחסי התלות של Python בפרויקט הזה, צריך גם ליצור ולהפעיל סביבה וירטואלית של Python, ואז להתקין בה את ספריות Python הנדרשות באמצעות pip.

  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: הודעות נפוצות של מאגר אחסון לפרוטוקולים שמשמשות בממשקי ה-API של Google.
    • ‫grpcio: ספריית gRPC ל-Python.
    • ‫requests: נדרש על ידי חלק מהתלויות כדי לשלוח בקשות HTTP.

יצירת הספריות של מאגר האחסון לפרוטוקולים

כדי לקיים אינטראקציה עם Universal Ledger API באמצעות gRPC, אפליקציית Python צריכה ספריות לקוח שעברו הידור מהגדרות מאגר האחסון לפרוטוקולים (.proto) של השירות. ההגדרות האלה מציינות את השירותים, ה-methods וסוגי ההודעות של ה-API.

בקטע הזה מוסבר איך להוריד את קובצי ה-.proto האלה מהמאגר של googleapis, ולהשתמש ב-grpcio-tools המותקן כדי ליצור את קוד המקור הנדרש ב-Python.

  1. משכפלים את מאגר ה-GitHub של googleapis, שבו מתפרסמות ההגדרות של מאגר האחסון לפרוטוקולים של Google APIs.

    git clone https://github.com/googleapis/googleapis.git
  2. יוצרים את ההגדרות של מאגר האחסון לפרוטוקולים ואת הקישורים של gRPC ל-Universal Ledger API.

    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.

בקוד, מחליפים את הערכים הזמניים הבאים לשמירת מקום (placeholder):

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud , לדוגמה my-project.
  • ‫REGION: האזור ב- Google Cloud שבו נמצאת נקודת הקצה של Universal Ledger, לדוגמה 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

המאמרים הבאים