响应流迭代器

search_stream 方法会返回 SearchGoogleAdsStreamResponse 对象的迭代器。

遍历流式传输响应

您可以遍历每个 GoogleAdsRow results,如以下代码示例所示:

def main(client: GoogleAdsClient, customer_id: str) -> None:
    ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService")

    query: str = """
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.id"""

    # Issues a search request using streaming.
    stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream(
        customer_id=customer_id, query=query
    )

    for batch in stream:
        rows: List[GoogleAdsRow] = batch.results
        for row in rows:
            print(
                f"Campaign with ID {row.campaign.id} and name "
                f'"{row.campaign.name}" was found.'
            )
      

每个 GoogleAdsRow 的结构由您在 Google Ads 查询语言 (GAQL) 查询中选择的字段决定。如需详细了解响应 结构,请参阅 Google Ads 查询语言。

将迭代器保留在范围内

调用 GoogleAdsService.search_stream时, 系统会返回流式传输响应迭代器。此迭代器在被使用时必须与 GoogleAdsService 客户端保持在同一范围内,以避免流中断或出现段错误。这是因为,一旦打开的 GoogleAdsService 对象超出范围,底层 gRPC Channel 对象就会被垃圾回收。如果 GoogleAdsService 对象在对 search_stream 的结果进行迭代时不再在范围内,则 Channel 对象可能已被销毁,导致迭代器尝试检索下一个值时出现未定义的行为。

以下代码演示了流式传输迭代器的不正确 用法:

def stream_response(client, customer_id, query):
    # The GoogleAdsService instance goes out of scope when this function
    # returns.
    ga_service = client.get_service(
        "GoogleAdsService", version="v26"
    )
    return ga_service.search_stream(customer_id=customer_id, query=query)


def main(client, customer_id):
    query = "SELECT campaign.name FROM campaign LIMIT 10"
    response = stream_response(client, customer_id, query=query)

    # Accessing the iterator in a different scope from where the service object
    # was created results in undefined behavior.
    for batch in response:
        print(batch)

在此代码中,GoogleAdsService 对象的创建范围与访问迭代器的范围不同。因此,Channel 对象可能会在迭代器使用整个响应之前被销毁。

请改为将流式传输迭代器与 GoogleAdsService 客户端保持在同一范围内,只要它正在使用:

def main(client, customer_id):
    ga_service = client.get_service(
        "GoogleAdsService", version="v26"
    )
    query = "SELECT campaign.name FROM campaign LIMIT 10"
    response = ga_service.search_stream(customer_id=customer_id, query=query)

    # Access the iterator in the same scope where the service object was
    # created.
    for batch in response:
        print(batch)