응답 스트림 반복기

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 Query Language (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)