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