服务和类型 getter

提取对在 Google Cloud 中使用 API 所需的所有各种 proto 类的引用 Python 可能很冗长,并且需要您对 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/。 version 目录下的所有代码均由系统生成,因此最好 请练习使用这些方法,而不是直接导入对象,以防出现 代码库结构更改。

以下示例说明了如何使用 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 类型。也就是说 因此可以轻松读取成员的值使用 campaign 实例 Python Repl 中的上一个示例:

>>> 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 的多个版本。虽然 v17 可能是最新版本,仍然是之前的版本 在停用之前均可访问。该库将包含单独的 proto 与每个活跃 API 版本相对应的消息类。访问邮件 类时,应在以下情况下提供 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_service 时指定版本, get_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 参考文档。