search_stream वाला तरीका, SearchGoogleAdsStreamResponse ऑब्जेक्ट का इटरेटर दिखाता है.
स्ट्रीम के जवाबों को बार-बार दोहराना
हर जवाब के results फ़ील्ड में मौजूद हर GoogleAdsRow को दोहराया जा सकता है. इसके लिए, कोड का यह उदाहरण देखें:
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 क्वेरी लैंग्वेज देखें.
इटरेटर को स्कोप में रखना
कॉल करने पर
GoogleAdsService.search_stream,
स्ट्रीमिंग रिस्पॉन्स इटरेटर वापस कर दिया जाता है. इस्तेमाल किए जाने के दौरान, इस इटरेटर को GoogleAdsService क्लाइंट के स्कोप में ही रहना चाहिए. इससे, स्ट्रीम के टूटने या सेगमेंटेशन की गड़बड़ियों से बचा जा सकता है. ऐसा इसलिए होता है, क्योंकि GoogleAdsService ऑब्जेक्ट के स्कोप से बाहर जाने के बाद, gRPC Channel ऑब्जेक्ट का गार्बेज कलेक्शन हो जाता है. अगर search_stream के नतीजे पर इटरेट करते समय GoogleAdsService ऑब्जेक्ट अब स्कोप में नहीं है, तो हो सकता है कि Channel ऑब्जेक्ट पहले ही नष्ट हो गया हो. इससे, जब इटरेटर अगली वैल्यू को वापस पाने की कोशिश करेगा, तब अनचाहा व्यवहार हो सकता है.
यहां दिए गए कोड में, स्ट्रीम इटरेटर के गलत इस्तेमाल का उदाहरण दिया गया है:
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 ऑब्जेक्ट को मिटा दिया जाए.
इसके बजाय, स्ट्रीमिंग इटरेटर को तब तक 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)