스트리밍 반복기

GoogleAdsService.search_stream를 호출하면 스트리밍 응답 반복자가 반환됩니다. 스트림 중단이나 세분화 결함을 방지하려면 이 반복자를 사용하는 동안 GoogleAdsService 클라이언트와 동일한 범위를 유지해야 합니다. 열린 GoogleAdsService 객체가 범위를 벗어나면 gRPC Channel 객체가 가비지로 수집되기 때문입니다. search_stream의 결과에 반복이 발생할 때까지 GoogleAdsService 객체가 더 이상 범위에 포함되지 않는 경우 Channel 객체가 이미 소멸되어 반복자가 다음 값을 검색하려고 할 때 정의되지 않은 동작이 발생할 수 있습니다.

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

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