Phương thức search_stream trả về một trình lặp của các đối tượng SearchGoogleAdsStreamResponse.
Bạn có thể lặp lại từng GoogleAdsRow trong trường results của từng phản hồi như trong ví dụ mã này.
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.' )
Cấu trúc của mỗi GoogleAdsRow được xác định bằng các trường mà bạn chọn trong truy vấn Ngôn ngữ truy vấn của Google Ads (GAQL). Để biết thêm thông tin về cấu trúc phản hồi, hãy xem Ngôn ngữ truy vấn Google Ads.
Khi gọi GoogleAdsService.search_stream, một trình lặp phản hồi truyền trực tuyến sẽ được trả về. Trình lặp này phải nằm trong cùng phạm vi với ứng dụng GoogleAdsService trong khi được dùng để tránh các luồng bị hỏng hoặc lỗi phân đoạn. Điều này là do đối tượng Channel gRPC được thu gom rác sau khi đối tượng GoogleAdsService mở nằm ngoài phạm vi.
Nếu đối tượng GoogleAdsService không còn trong phạm vi vào thời điểm quá trình lặp lại xảy ra trên kết quả của search_stream, thì đối tượng Channel có thể đã bị huỷ, gây ra hành vi không xác định khi trình lặp cố gắng truy xuất giá trị tiếp theo.
Đoạn mã sau đây minh hoạ cách sử dụng trình lặp truyền phát không chính xác:
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.
Trong mã này, đối tượng GoogleAdsService được tạo trong một phạm vi khác với phạm vi mà trình lặp được truy cập. Do đó, đối tượng Channel có thể bị huỷ trước khi trình lặp sử dụng toàn bộ phản hồi.
Thay vào đó, trình lặp lại truyền phát trực tiếp phải nằm trong cùng phạm vi với ứng dụng GoogleAdsService cho đến khi được sử dụng:
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.