服務和類型 Getter

擷取在 Python 中使用 API 所需的各種 proto 類別參照可能很冗長,而且您必須對 API 有基本的瞭解,或經常進行環境切換,才能參考 proto 或說明文件。

用戶端的 get_serviceget_type 方法

這兩種 getter 方法可讓您在 API 中擷取任何服務或類型物件。get_service 方法可用來擷取服務用戶端。get_type 用於任何其他物件。服務用戶端類別是在版本路徑 google/ads/googleads/v*/services/services/ 下的程式碼中定義,所有類型則定義於各種物件類別 google/ads/googleads/v*/common|enums|errors|resources|services/types/ 下。系統會產生版本目錄下的所有程式碼,因此如果程式碼集結構有所變更,最佳做法是使用這些方法,而不要直接匯入物件。

以下範例說明如何使用 get_service 方法擷取 GoogleAdsService 用戶端的執行個體。

from google.ads.googleads.client import GoogleAdsClient

# "load_from_storage" loads your API credentials from disk so they
# can be used for service initialization. Providing the optional `version`
# parameter means that the v17 version of GoogleAdsService will
# be returned.
client = GoogleAdsClient.load_from_storage(version="v17")
googleads_service = client.get_service("GoogleAdsService")

以下範例說明如何使用 get_type 方法擷取 Campaign 執行個體。

from google.ads.googleads.client import GoogleAdsClient

client = GoogleAdsClient.load_from_storage(version="v17")
campaign = client.get_type("Campaign")

列舉

雖然您可以使用 get_type 方法擷取列舉,但每個 GoogleAdsClient 執行個體也具有 enums 屬性,可使用與 get_type 方法相同的機制動態載入 Enum。這個介面比使用 get_type 更簡潔易讀:

client = GoogleAdsClient.load_from_storage(version=v17)

campaign = client.get_type("Campaign")
campaign.status = client.enums.CampaignStatusEnum.PAUSED

列舉的 Proto 物件欄位在 Python 中會以原生 enum 類型表示。也就是說,您可以輕鬆讀取會員的值。在 Python repl 中使用先前範例中的 campaign 例項:

>>> print(campaign.status)
CampaignStatus.PAUSED
>>> type(campaign.status)
<enum 'CampaignStatus'>
>>> print(campaign.status.value)
3

有時候,瞭解與上述列舉值對應的欄位名稱會很有幫助。您可以使用 name 屬性存取這項資訊:

>>> print(campaign.status.name)
'PAUSED'
>>> type(campaign.status.name)
<class 'str'>

與列舉互動的方式,取決於您將 use_proto_plus 設定設為 true 還是 false。如要進一步瞭解這兩個介面,請參閱 protobuf 訊息說明文件

版本管理

同時維護多個 API 版本。雖然 v17 可能是最新版本,但在停用前仍可存取。程式庫會包含對應於每個有效 API 版本的不同 proto 訊息類別。如要存取特定版本的訊息類別,請在初始化用戶端時提供 version 關鍵字參數,使其一律傳回該指定版本的例項:

client = GoogleAdsService.load_from_storage(version="/google-ads/api/reference/rpc/v17/")
# The Campaign instance will be from the v17 version of the API.
campaign = client.get_type("Campaign")

您也可以在呼叫 get_serviceget_type 方法時指定版本。這樣做會覆寫在初始化用戶端時提供的版本:

client = GoogleAdsService.load_from_storage()
# This will load the v17 version of the GoogleAdsService.
googleads_service = client.get_service(
    "GoogleAdsService", version="v17")

client = GoogleAdsService.load_from_storage(version="v17")
# This will load the v15 version of a Campaign.
campaign = client.get_type("Campaign", version="v15")

如未提供 version 關鍵字參數,程式庫會預設使用最新版本。您可以在 API 參考資料說明文件的左側導覽部分找到最新及其他可用版本的更新清單。