search_stream 方法會傳回 SearchGoogleAdsStreamResponse 物件的疊代器。
疊代串流回應
您可以逐一查看每個回應 results 欄位中的每個 GoogleAdsRow,如以下程式碼範例所示:
def main(client: GoogleAdsClient, customer_id: str) -> None: ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService") query: str = """ SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id""" # Issues a search request using streaming. stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream( customer_id=customer_id, query=query ) for batch in stream: rows: List[GoogleAdsRow] = batch.results for row in rows: print( f"Campaign with ID {row.campaign.id} and name " f'"{row.campaign.name}" was found.' )
每個 GoogleAdsRow 的結構取決於您在 Google Ads 查詢語言 (GAQL) 查詢中選取的欄位。如要進一步瞭解回應結構,請參閱「Google Ads 查詢語言」。
將疊代器保留在範圍內
呼叫 GoogleAdsService.search_stream 時,系統會傳回串流回應疊代器。這個疊代器必須與 GoogleAdsService 用戶端保持在相同範圍內,同時避免串流中斷或區隔錯誤。這是因為一旦開啟的 GoogleAdsService 物件超出範圍,基礎 gRPC Channel 物件就會遭到垃圾收集。如果 search_stream 的結果發生疊代時,GoogleAdsService 物件已不在範圍內,則 Channel 物件可能已刪除,導致疊代器嘗試擷取下一個值時發生未定義的行為。
以下程式碼示範串流疊代器的錯誤用法:
def stream_response(client, customer_id, query):
# The GoogleAdsService instance goes out of scope when this function
# returns.
ga_service = client.get_service(
"GoogleAdsService", version="v26"
)
return ga_service.search_stream(customer_id=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)
# Accessing the iterator in a different scope from where the service object
# was created results in undefined behavior.
for batch in response:
print(batch)
在這段程式碼中,GoogleAdsService 物件是在與疊代器存取位置不同的範圍內建立。因此,在疊代器使用整個回應之前,Channel 物件可能會遭到刪除。
請改為將串流疊代器保留在與 GoogleAdsService 用戶端相同的範圍內,只要使用該疊代器即可:
def main(client, customer_id):
ga_service = client.get_service(
"GoogleAdsService", version="v26"
)
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 where the service object was
# created.
for batch in response:
print(batch)