服务和类型 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 方法相同的机制动态加载枚举。与使用 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 参考文档的左侧导航部分找到最新版本和其他可用版本的更新列表。