服务和类型 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 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 方法相同的机制动态加载枚举。与使用 get_type 相比,此接口更易于阅读:

client = GoogleAdsClient.load_from_storage(version=v16)

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 同时维护多个版本。虽然 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_serviceget_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 参考文档的左侧导航部分。