调用时
GoogleAdsService.search_stream
、
系统会返回流式响应迭代器。此迭代器应保留在
使用与 GoogleAdsService
客户端相同的作用域,以免
或分段故障。这是因为 gRPC Channel
对象
一旦打开的 GoogleAdsService
对象超出范围,系统就会执行垃圾回收。
如果 GoogleAdsService
对象在迭代时不再位于作用域内
search_stream
的结果时,Channel
对象可能已经
已销毁,导致在迭代器尝试检索
下一个值。
以下代码演示了流式迭代器的错误用法:
def stream_response(client, customer_id, query):
return client.get_service("GoogleAdsService", version="v17").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="v17")
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.