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):
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.