เมธอด search_stream จะแสดงผลตัวทำซ้ำของออบเจ็กต์ SearchGoogleAdsStreamResponse
ทำซ้ำผ่านการตอบกลับสตรีม
คุณสามารถทำซ้ำ GoogleAdsRow แต่ละรายการในฟิลด์ results ของการตอบกลับแต่ละรายการได้ ดังที่แสดงในตัวอย่างโค้ดต่อไปนี้
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
เก็บ Iterator ไว้ในขอบเขต
เมื่อเรียกใช้
GoogleAdsService.search_stream
ระบบจะแสดงผลตัววนซ้ำการตอบกลับแบบสตรีมมิง ตัวทำซ้ำนี้ต้องอยู่ในขอบเขตเดียวกับไคลเอ็นต์ GoogleAdsService ขณะใช้งานเพื่อหลีกเลี่ยงสตรีมที่เสียหายหรือข้อผิดพลาดในการแบ่งกลุ่ม เนื่องจากออบเจ็กต์ Channel gRPC ที่สำคัญจะถูกรวบรวมขยะเมื่อออบเจ็กต์ GoogleAdsService ที่เปิดอยู่ออกนอกขอบเขต หากออบเจ็กต์ GoogleAdsService ไม่อยู่ในขอบเขตอีกต่อไปเมื่อเกิดการทำซ้ำในผลลัพธ์ของ search_stream ออบเจ็กต์ Channel อาจถูกทำลายไปแล้ว ซึ่งทำให้เกิดลักษณะการทำงานที่ไม่ได้กำหนดไว้เมื่อ Iterator พยายามดึงค่าถัดไป
โค้ดต่อไปนี้แสดงการใช้งานตัวทำซ้ำสตรีมที่ไม่ถูกต้อง
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 อาจถูกทำลายก่อนที่ Iterator จะใช้การตอบกลับทั้งหมด
แต่ให้เก็บตัวทำซ้ำสตรีมมิงไว้ในขอบเขตเดียวกับไคลเอ็นต์ 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)