串流疊代器

撥打電話時 GoogleAdsService.search_stream、 會傳回串流回應疊代器該疊代器應維持在 與 GoogleAdsService 用戶端相同的範圍,避免浪費 損壞串流或區隔錯誤這是因為 gRPC Channel 物件 當開放式 GoogleAdsService 物件超出範圍時,就會進行垃圾收集。 如果 GoogleAdsService 物件在疊代時不在範圍內 發生在 search_stream 的結果上,Channel 物件可能已 已刪除,在疊代器嘗試擷取 下一個值。

以下程式碼示範如何使用串流疊代器不正確

def stream_response(client, customer_id, query):
    return client.get_service("GoogleAdsService", version="v17").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="v17")
    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.