Google Ads API для Python: у объекта "_Rendezvous" нет атрибута "request_id"

Я пытался скопировать следующий пример кода для API объявлений Google, используя клиентскую библиотеку Python. Позвольте мне предисловие, сказав, что я завершил процесс аутентификации и настроил google-ads.yaml файл с developer_token, client_id, client_secret, refresh_token, а также login_customer_id, Пример кода, который я хочу скопировать, приведен ниже, вы также можете просмотреть его в следующем репозитории GitHub.

# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to get all campaigns.
To add campaigns, run add_campaigns.py.
"""

from __future__ import absolute_import

import argparse
import six
import sys

import google.ads.google_ads.client


_DEFAULT_PAGE_SIZE = 1000


def main(client, customer_id, page_size):
    ga_service = client.get_service('GoogleAdsService')

    query = ('SELECT campaign.id, campaign.name FROM campaign '
             'ORDER BY campaign.id')

    results = ga_service.search(customer_id, query=query,page_size=page_size)

    try:
        for row in results:
            print('Campaign with ID %d and name "%s" was found.'
                  % (row.campaign.id.value, row.campaign.name.value))
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)


if __name__ == '__main__':
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = (google.ads.google_ads.client.GoogleAdsClient
                         .load_from_storage('google-ads.yaml'))

    parser = argparse.ArgumentParser(
        description='Lists all campaigns for specified customer.')
    # The following argument(s) should be provided to run the example.
    parser.add_argument('-c', '--customer_id', type=six.text_type,
                        required=True, help='The Google Ads customer ID.')
    args = parser.parse_args()

main(google_ads_client, args.customer_id, _DEFAULT_PAGE_SIZE)

Я попытался запустить приведенный выше код несколькими способами в командной строке следующим образом:

> python get_campaigns.py --customer_id 'xxx-xxx-xxxx'
> python get_campaign.py --customer_id 'xxxxxxxxxx'

Я даже закомментировал строки после объявления переменной google_ads_client и просто ввел идентификатор клиента вручную

main(google_ads_client, 'xxxxxxxxxx', _DEFAULT_PAGE_SIZE)
main(google_ads_client, 'xxx-xxx-xxxx', _DEFAULT_PAGE_SIZE)

и запустил сценарий таким образом. Для всех этих случаев я все еще получал ту же ошибку

AttributeError: '_Rendezvous' object has no attribute 'request_id'

Любая помощь приветствуется. Спасибо.

0 ответов

Попробуй это..

python get_campaigns.py --customer_id "123456789"

без кавычек

На самом деле вам не нужно определять или запрашивать размер страницы. Вы не предоставляете токен, который вам нужен, но не предоставляет.

Учитывая, что ваш запрос предназначен только для запроса кампаний, я бы посоветовал вам использовать эту версию без необходимости разбиения на страницы или токена (разбиение на страницы не требуется в новом API Google Рекламы, если вы не хотите фактически реализовать разбиение на страницы самостоятельно, что я вам не верю делать).

Эта версия даст вам те же результаты, что и первая, без разбиения на страницы.

Другие вопросы по тегам