在 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 v24 version of GoogleAdsService will
# be returned.
client = GoogleAdsClient.load_from_storage(version="v24")
googleads_service = client.get_service("GoogleAdsService")
以下示例展示了如何使用 get_type 方法检索
Campaign 实例。
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage(version="v24")
campaign = client.get_type("Campaign")
枚举
虽然您可以使用 get_type 方法检索枚举,但每个 GoogleAdsClient 实例也有一个 enums 属性,该属性使用与 get_type 方法相同的机制动态加载枚举。此接口旨在比使用 get_type 更简单易读:
client = GoogleAdsClient.load_from_storage(version=v24)
campaign = client.get_type("Campaign")
campaign.status = client.enums.CampaignStatusEnum.PAUSED
作为枚举的 Proto 对象字段在 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 的多个版本。虽然 v24 可能是最新版本,但在停用之前,您仍然可以访问之前的版本。该库将包含与每个活跃 API 版本对应的单独 proto 消息类。如需访问特定版本的消息类,请在初始化客户端时提供 version 关键字形参,以便它始终返回给定版本的实例:
client = GoogleAdsService.load_from_storage(version="/google-ads/api/reference/rpc/v24/")
# The Campaign instance will be from the v24 version of the API.
campaign = client.get_type("Campaign")
您还可以在调用 get_service 和 get_type 方法时指定版本。这样做会替换初始化客户端时提供的版本:
client = GoogleAdsService.load_from_storage()
# This will load the v24 version of the GoogleAdsService.
googleads_service = client.get_service(
"GoogleAdsService", version="v24")
client = GoogleAdsService.load_from_storage(version="v24")
# This will load the v22 version of a Campaign.
campaign = client.get_type("Campaign", version="v22")
如果未提供 version 关键字形参,该库将默认使用最新版本。如需查看最新版本和其他可用版本的更新列表
,请参阅
API 参考文档的左侧导航栏部分。