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