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