流式迭代器

调用 GoogleAdsService.search_stream 时,系统会返回一个流式响应迭代器。使用此迭代器时,它应保持与 GoogleAdsService 客户端相同的作用域,以避免数据流中断或分段错误。这是因为,当打开的 GoogleAdsService 对象超出作用域时,gRPC Channel 对象会被垃圾回收。如果在对 search_stream 的结果进行迭代时,GoogleAdsService 对象已不在作用域内,则 Channel 对象可能已被销毁,从而导致迭代器尝试检索下一个值时出现未定义的行为。

以下代码演示了流式迭代器的错误用法:

def stream_response(client, customer_id, query):
    return client.get_service("GoogleAdsService", version="v18").search_stream(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)
    # Access the iterator in a different scope from where the service object was created.
    try:
        for batch in response:
            # Iterate through response, expect undefined behavior.

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

相反,在使用期间,流式迭代器应保持与 GoogleAdsService 客户端相同的范围:

def main(client, customer_id):
    ga_service = client.get_service("GoogleAdsService", version="v18")
    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 as where the service object was created.
    try:
        for batch in response:
            # Successfully iterate through response.