使用 Python 用戶端程式庫連線至 Spanner Omni

Spanner 的 Python 用戶端程式庫與 Spanner Omni 搭配運作的方式,與 Spanner 相同。本文說明如何設定 Python 用戶端程式庫,建立與 Spanner Omni 的安全連線。建立用戶端時,您可以設定用戶端選項來建立這些連線。

Python 用戶端程式庫支援純文字、TLS、TLS (含憑證) 和 mTLS 連線。

詳情請參閱 Spanner 說明文件中的「開始透過 Python 使用 Spanner」。

事前準備

如要搭配使用 Python 用戶端程式庫與 Spanner Omni,請使用 Python 用戶端程式庫 3.72.0 以上版本。

如要安裝 Spanner Omni Python 套件,請執行下列指令:

pip install google-cloud-spanner>=3.72.0

設定 Client 物件

設定 Client 物件時,請在 client_options 中指定 Spanner Omni 端點,並指定 instance_type=InstanceType.OMNI

以下範例說明如何為各項支援的安全性設定設定 Client 物件:

純文字

如要建立純文字連線,請指定 instance_type=InstanceType.OMNIuse_plain_text=True

from google.cloud import spanner
from google.cloud.spanner_v1 import InstanceType

spanner_client = spanner.Client(
    client_options={"api_endpoint": "ENDPOINT"},
    instance_type=InstanceType.OMNI,
    use_plain_text=True,
)

更改下列內容:

  • ENDPOINT:Spanner Omni 執行個體的端點。

TLS

如要建立 TLS 連線,請使用 ca_certificate 指定 CA 憑證的路徑:

from google.cloud import spanner
from google.cloud.spanner_v1 import InstanceType

spanner_client = spanner.Client(
    client_options={"api_endpoint": "ENDPOINT"},
    instance_type=InstanceType.OMNI,
    ca_certificate="PATH_TO_CA_CERT",
)

更改下列內容:

  • ENDPOINT:Spanner Omni 執行個體的端點。

  • PATH_TO_CA_CERT:CA 憑證檔案的路徑。

使用認證資訊進行 TLS 驗證

如要透過使用者名稱和密碼驗證建立 TLS 連線,請一併指定 usernamepassword 參數以及 CA 憑證:

from google.cloud import spanner
from google.cloud.spanner_v1 import InstanceType

spanner_client = spanner.Client(
    client_options={"api_endpoint": "ENDPOINT"},
    instance_type=InstanceType.OMNI,
    ca_certificate="PATH_TO_CA_CERT",
    username="USERNAME",
    password="PASSWORD",
)

更改下列內容:

  • ENDPOINT:Spanner Omni 執行個體的端點。

  • PATH_TO_CA_CERT:CA 憑證檔案的路徑。

  • USERNAME:Spanner Omni 使用者的使用者名稱。

  • PASSWORD:Spanner Omni 使用者的密碼。

mTLS

如要建立相互傳輸層安全性 (mTLS) 連線,請指定 CA 憑證、用戶端憑證和私密用戶端金鑰:

from google.cloud import spanner
from google.cloud.spanner_v1 import InstanceType

spanner_client = spanner.Client(
    client_options={"api_endpoint": "ENDPOINT"},
    instance_type=InstanceType.OMNI,
    ca_certificate="PATH_TO_CA_CERT",
    client_certificate="PATH_TO_CLIENT_CERT",
    client_key="PATH_TO_CLIENT_KEY",
)

更改下列內容:

  • ENDPOINT:Spanner Omni 執行個體的端點。

  • PATH_TO_CA_CERT:CA 憑證檔案的路徑。

  • PATH_TO_CLIENT_CERT:用戶端憑證檔案的路徑。

  • PATH_TO_CLIENT_KEY:用戶端私密金鑰檔案的路徑。

取得資料庫

設定 Client 物件後,即可取得資料庫。由於 Spanner Omni 不會使用 Google Cloud 專案或執行個體 ID,因此建立 Instance 時,請為執行個體 ID 指定 default

instance = spanner_client.instance("default")
database = instance.database("DATABASE_ID")

更改下列內容:

  • DATABASE_ID:Spanner Omni 資料庫的 ID。