如何操纵Google Ads API的枚举对象 - python

问题描述 投票:3回答:2

我正在使用python客户端库连接到Google Ads的API。

    ga_service = client_service.get_service('GoogleAdsService')
    query = ('SELECT campaign.id, campaign.name, campaign.advertising_channel_type '
            'FROM campaign WHERE date BETWEEN \''+fecha+'\' AND \''+fecha+'\'')

    response = ga_service.search(<client_id>, query=query,page_size=1000)
    result = {}
    result['campanas'] = []

    try:
        for row in response:
            print row
            info = {}
            info['id'] = row.campaign.id.value
            info['name'] = row.campaign.name.value
            info['type'] = row.campaign.advertising_channel_type

当我解析值时,这是我得到的结果:

{
  "campanas": [
    {
      "id": <campaign_id>, 
      "name": "Lanzamiento SIKU", 
      "type": 2
    }, 
    {
      "id": <campaign_id>, 
      "name": "lvl1 - website traffic", 
      "type": 2
    }, 
    {
      "id": <campaign_id>, 
      "name": "Lvl 2 - display", 
      "type": 3
    }
  ]
}

为什么我得到一个结果[“type”]的整数?当我检查回溯调用时,我可以看到一个字符串:

campaign {
  resource_name: "customers/<customer_id>/campaigns/<campaign_id>"
  id {
    value: 397083380
  }
  name {
    value: "Lanzamiento SIKU"
  }
  advertising_channel_type: SEARCH
}

campaign {
  resource_name: "customers/<customer_id>/campaigns/<campaign_id>"
  id {
    value: 1590766475
  }
  name {
    value: "lvl1 - website traffic"
  }
  advertising_channel_type: SEARCH
}

campaign {
  resource_name: "customers/<customer_id>/campaigns/<campaign_id>"
  id {
    value: 1590784940
  }
  name {
    value: "Lvl 2 - display"
  }
  advertising_channel_type: DISPLAY
}

我搜索了Documentation for the API并发现它是因为字段:advertising_channel_type是数据类型:枚举。如何操作Enum类的这个对象来获取字符串值?他们的文档中没有关于此的有用信息。

请帮忙 !!

python enums google-api google-adwords
2个回答
2
投票

Enum有一些方法可以在索引和字符串之间进行转换

channel_types = client_service.get_type('AdvertisingChannelTypeEnum')

channel_types.AdvertisingChannelType.Value('SEARCH')
# => 2
channel_types.AdvertisingChannelType.Name(2)
# => 'SEARCH'

这可以通过查看文档字符串找到,例如

channel_types.AdvertisingChannelType.__doc__
# => 'A utility for finding the names of enum values.'

0
投票

只需解决它,创建一个列表

lookup_list = ['DISPLAY', 'HOTEL', 'SEARCH', 'SHOPPING', 'UNKNOWN', 'UNSPECIFIED', 'VIDEO']

并将最后一行中的作业更改为

info['type'] = lookup_list[row.campaign.advertising_channel_type]
© www.soinside.com 2019 - 2024. All rights reserved.