You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Ads API更高效获取登录用户的客户名称与货币代码?

更高效获取Google Ads客户名称与货币代码的方法

你的当前实现需要对每个客户单独发起查询请求,当客户数量较多时会产生大量HTTP调用,效率较低。以下是两种更高效的实现方式:


方法1:使用BatchJob批量提交查询

通过Google Ads API的BatchJobService,将所有客户的查询请求打包成一个批量任务,仅需一次HTTP调用即可获取所有结果,大幅减少请求开销,适合客户数量较多的场景。

示例代码:

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.v14.services.types.batch_job_service import (
    BatchJobOperation,
    SearchGoogleAdsRequestOperation,
)
import time

def get_all_customers_with_batch_job(client):
    # 获取可访问客户列表
    customer_service = client.get_service("CustomerService")
    accessible_customers = customer_service.list_accessible_customers().resource_names
    customer_ids = [entry.split('/')[1] for entry in accessible_customers]
    
    # 创建BatchJob(使用任意有权限的客户ID即可)
    batch_job_service = client.get_service("BatchJobService")
    batch_job_op = client.get_type("BatchJobOperation")
    batch_job_op.create = client.get_type("BatchJob")
    batch_job_response = batch_job_service.mutate_batch_job(
        customer_id=customer_ids[0],
        operation=batch_job_op
    )
    batch_job_resource = batch_job_response.result.resource_name
    
    # 批量生成查询请求
    ga_service = client.get_service("GoogleAdsService")
    query = """
        SELECT
            customer.descriptive_name,
            customer.currency_code
        FROM customer
        LIMIT 1
    """
    operations = []
    
    for cid in customer_ids:
        search_req = client.get_type("SearchGoogleAdsRequest")
        search_req.customer_id = cid
        search_req.query = query
        
        op = BatchJobOperation()
        op.search_google_ads_request.request = search_req
        operations.append(op)
    
    # 将请求添加到BatchJob
    batch_job_service.add_batch_job_operations(
        resource_name=batch_job_resource,
        operations=operations
    )
    
    # 轮询等待任务完成(生产环境建议异步处理)
    while True:
        job_status = batch_job_service.get_batch_job(batch_job_resource).status
        if job_status == client.enums.BatchJobStatusEnum.DONE:
            break
        time.sleep(5)
    
    # 处理返回结果
    apps = []
    results = batch_job_service.list_batch_job_results(batch_job_resource)
    for res in results:
        if res.search_google_ads_response:
            customer = list(res.search_google_ads_response.results)[0].customer
            cid = customer.resource_name.split('/')[1]
            apps.append({
                'customer_id': cid,
                'name': customer.descriptive_name,
                'currency': customer.currency_code
            })
    
    # 清理BatchJob(可选)
    cleanup_op = client.get_type("BatchJobOperation")
    cleanup_op.remove = batch_job_resource
    batch_job_service.mutate_batch_job(customer_id=customer_ids[0], operation=cleanup_op)
    
    return apps

方法2:并发请求(适合中小规模客户列表)

使用线程池同时发起多个查询请求,缩短总耗时。注意控制并发数,避免触发API配额限制。

示例代码:

from concurrent.futures import ThreadPoolExecutor
from google.ads.googleads.client import GoogleAdsClient

def fetch_customer_details(client, ga_service, customer_id):
    query = """
        SELECT
            customer.descriptive_name,
            customer.currency_code
        FROM customer
        LIMIT 1
    """
    request = client.get_type("SearchGoogleAdsRequest")
    request.customer_id = customer_id
    request.query = query
    response = ga_service.search(request=request)
    customer = list(response)[0].customer
    return {
        'customer_id': customer_id,
        'name': customer.descriptive_name,
        'currency': customer.currency_code
    }

def get_all_customers_concurrently(client):
    customer_service = client.get_service("CustomerService")
    accessible_customers = customer_service.list_accessible_customers().resource_names
    customer_ids = [entry.split('/')[1] for entry in accessible_customers]
    
    # 提前初始化GoogleAdsService,避免重复创建实例
    ga_service = client.get_service("GoogleAdsService")
    
    # 并发执行查询,max_workers根据API配额调整(建议10-20)
    apps = []
    with ThreadPoolExecutor(max_workers=15) as executor:
        futures = [executor.submit(fetch_customer_details, client, ga_service, cid) for cid in customer_ids]
        for future in futures:
            apps.append(future.result())
    
    return apps

基础代码优化(不改变请求方式的前提下)

如果暂时不想用批量或并发,也可以对原有代码做小优化,减少重复操作:

def get_all_customers_basic_optimized(client):
    customer_service = client.get_service("CustomerService")
    app_list = customer_service.list_accessible_customers().resource_names
    # 提前初始化GoogleAdsService
    ga_service = client.get_service("GoogleAdsService")
    query = """
        SELECT
            customer.descriptive_name,
            customer.currency_code
        FROM customer
        LIMIT 1
    """
    
    apps = []
    for entry in app_list:
        customer_id = entry.split('/')[1]
        request = client.get_type("SearchGoogleAdsRequest")
        request.customer_id = customer_id
        request.query = query
        response = ga_service.search(request=request)
        customer = list(response)[0].customer
        apps.append({
            'customer_id': customer_id,
            'name': customer.descriptive_name,
            'currency': customer.currency_code
        })
    
    return apps

内容的提问来源于stack exchange,提问作者jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:57:30