스트리밍 반복기

GoogleAdsService.search_stream를 호출하면 스트리밍 응답 반복자가 반환됩니다. 이 반복자는 스트림이 중단되거나 세그먼트 오류가 발생하지 않도록 사용되는 동안 GoogleAdsService 클라이언트와 동일한 범위에 있어야 합니다. 열린 GoogleAdsService 객체가 범위를 벗어나면 gRPC Channel 객체가 가비지 컬렉션되기 때문입니다. search_stream 결과에 대한 반복이 발생할 때 GoogleAdsService 객체가 더 이상 범위에 없으면 Channel 객체가 이미 소멸되어 있을 수 있으므로 반복자가 다음 값을 가져오려고 할 때 정의되지 않은 동작이 발생합니다.

다음 코드는 스트리밍 반복자의 잘못된 사용법을 보여줍니다.

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