擷取在 Python 中使用 API 所需的各種 proto 類別參照,可能較為詳細,且您必須對 API 有內建瞭解,或經常執行情境切換,以便參考 proto 或說明文件。
用戶端的 get_service
和 get_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 v16 version of GoogleAdsService will
# be returned.
client = GoogleAdsClient.load_from_storage(version="v16")
googleads_service = client.get_service("GoogleAdsService")
以下範例說明如何使用 get_type
方法擷取 Campaign
執行個體。
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage(version="v16")
campaign = client.get_type("Campaign")
列舉
雖然您可以使用 get_type
方法擷取列舉,但每個 GoogleAdsClient
執行個體也都有 enums
屬性,可使用與 get_type
方法相同的機制動態載入 Enum。這個介面比使用 get_type
更簡單易讀:
client = GoogleAdsClient.load_from_storage(version=v16)
campaign = client.get_type("Campaign")
campaign.status = client.enums.CampaignStatusEnum.PAUSED
列舉的 Proto 物件欄位會以原生 enum 類型在 Python 中表示。這表示您可以輕鬆讀取成員的值。在 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。雖然 v16
可能是最新版本,但先前版本在停用前仍可存取。程式庫會包含對應至各個有效 API 版本的個別 proto 訊息類別。如要存取特定版本的訊息類別,請在初始化用戶端時提供 version
關鍵字參數,使其一律傳回該版本的執行個體:
client = GoogleAdsService.load_from_storage(version="/google-ads/api/reference/rpc/v16/")
# The Campaign instance will be from the v16 version of the API.
campaign = client.get_type("Campaign")
您也可以在呼叫 get_service
和 get_type
方法時指定版本。這項操作會覆寫您初始化用戶端時提供的版本:
client = GoogleAdsService.load_from_storage()
# This will load the v16 version of the GoogleAdsService.
googleads_service = client.get_service(
"GoogleAdsService", version="v16")
client = GoogleAdsService.load_from_storage(version="v16")
# This will load the v14 version of a Campaign.
campaign = client.get_type("Campaign", version="v14")
如未提供 version
關鍵字參數,程式庫會預設為使用最新版本。您可以在 API 參考資料說明文件的左側導覽面板部分,查看最新及其他可用版本的更新清單。