In [1]:
#!/usr/bin/env python
from googleads import adwords
In [2]:
def DisplayAccountTree(account, accounts, links, depth=0):
"""Displays an account tree.
Args:
account: dict The account to display.
accounts: dict Map from customerId to account.
links: dict Map from customerId to child links.
depth: int Depth of the current account in the tree.
"""
prefix = '-' * depth * 2
print '%s%s, %s' % (prefix, account['customerId'], account['name'])
if account['customerId'] in links:
for child_link in links[account['customerId']]:
child_account = accounts[child_link['clientCustomerId']]
DisplayAccountTree(child_account, accounts, links, depth + 1)
def get_accounts(client):
# Initialize appropriate service.
managed_customer_service = client.GetService('ManagedCustomerService', version='v201705')
# Construct selector to get all accounts.
offset = 0
selector = {
'fields': ['CustomerId', 'Name'],
'paging': {
'startIndex': str(offset),
'numberResults': str(PAGE_SIZE)
}
}
more_pages = True
accounts = {}
child_links = {}
parent_links = {}
root_account = None
while more_pages:
# Get serviced account graph.
page = managed_customer_service.get(selector)
if 'entries' in page and page['entries']:
# Create map from customerId to parent and child links.
if 'links' in page:
for link in page['links']:
if link['managerCustomerId'] not in child_links:
child_links[link['managerCustomerId']] = []
child_links[link['managerCustomerId']].append(link)
if link['clientCustomerId'] not in parent_links:
parent_links[link['clientCustomerId']] = []
parent_links[link['clientCustomerId']].append(link)
# Map from customerID to account.
for account in page['entries']:
accounts[account['customerId']] = account
offset += PAGE_SIZE
selector['paging']['startIndex'] = str(offset)
more_pages = offset < int(page['totalNumEntries'])
# Find the root account.
for customer_id in accounts:
if customer_id not in parent_links:
root_account = accounts[customer_id]
# Display account tree.
if root_account:
print 'CustomerId, Name'
DisplayAccountTree(root_account, accounts, child_links, 0)
else:
print 'Unable to determine a root account'
In [ ]:
# Initialize client object.
PAGE_SIZE = 500
adwords_client = adwords.AdWordsClient.LoadFromStorage()
get_accounts(adwords_client)
In [ ]: