服務和類型 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 v20 version of GoogleAdsService will
# be returned.
client = GoogleAdsClient.load_from_storage(version="v20")
googleads_service = client.get_service("GoogleAdsService")

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

from google.ads.googleads.client import GoogleAdsClient

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

列舉

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

client = GoogleAdsClient.load_from_storage(version=v20)

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

Python 會以原生 enum 型別表示列舉的 Proto 物件欄位。也就是說,您可以輕鬆讀取成員的值。在 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 設定為 truefalse 而異。如要進一步瞭解這兩個介面,請參閱 protobuf 訊息說明文件

版本管理

同時維護多個 API 版本。雖然 v20 是最新版本,但舊版仍可存取,直到終止服務為止。程式庫會包含對應各個有效 API 版本的獨立 Proto 訊息類別。如要存取特定版本的訊息類別,請在初始化用戶端時提供 version 關鍵字參數,確保系統一律從該版本傳回執行個體:

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

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

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

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

如果未提供 version 關鍵字參數,程式庫預設會使用最新版本。如要查看最新版本和其他可用版本的更新清單,請前往 API 參考資料文件的左側導覽部分。