串流疊代器

search_stream 方法會傳回 SearchGoogleAdsStreamResponse 物件的疊代器。

如這個程式碼範例所示,您可以逐一檢查每個回應的 GoogleAdsRow results 欄位。

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 物件就會進行垃圾收集。如果 GoogleAdsService 物件在 search_stream 結果上發生疊代時已不在範圍內,Channel 物件可能已遭破壞,導致疊代器嘗試擷取下一個值時發生未定義的行為。

下列程式碼示範錯誤的串流迭代器用法:

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