呼叫 GoogleAdsService.search_stream
時,系統會傳回串流回應疊代器。使用時,此疊代器應與 GoogleAdsService
用戶端位於相同範圍,以免發生中斷的串流或區隔錯誤。這是因為當開放式 GoogleAdsService
物件超出範圍時,gRPC Channel
物件會遭到垃圾收集。如果在 search_stream
結果發生疊代時,GoogleAdsService
物件已不在範圍內,則 Channel
物件可能已遭到銷毀,導致疊代器嘗試擷取下一個值時發生未定義的行為。
以下程式碼示範如何錯誤使用串流疊代器:
def stream_response(client, customer_id, query):
return client.get_service("GoogleAdsService", version="v19").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="v19")
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.