レスポンス ストリーム イテレータ

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 広告クエリ言語(GAQL)クエリで選択したフィールドによって決まります。レスポンス 構造の詳細については、Google 広告クエリ言語をご覧ください。

イテレータをスコープ内に保持する

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)