作爲另一個答覆中提到,你可以使用一個單獨的線程,而主線程繼續輪詢操作。或者,您可以將返回的操作的operation.name
傳遞給單獨的服務,並讓該其他服務處理輪詢。例如,在實踐中,調用長時間運行操作的服務可以發佈operation.name
到Pub/Sub主題。
下面是按名稱查找來獲取一個長期運行的操作的可能方式:
from oauth2client.client import GoogleCredentials
from googleapiclient import discovery
credentials = GoogleCredentials.get_application_default()
speech_service = discovery.build('speech', 'v1', credentials=credentials)
operation_name = .... # operation.name
get_operation_request = speech_service.operations().get(name=operation_name)
# response is a dictionary
response = get_operation_response.execute()
# handle polling
retry_count = 100
while retry_count > 0 and not response.get('done', False):
retry_count -= 1
time.sleep(60)
response = get_operation_response.execute()
當操作完成後,response
字典可能類似於以下內容:
{u'done': True,
u'metadata': {u'@type': u'type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata',
u'lastUpdateTime': u'2017-06-21T19:38:14.522280Z',
u'progressPercent': 100,
u'startTime': u'2017-06-21T19:38:13.599009Z'},
u'name': u'...................',
u'response': {u'@type': u'type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse',
u'results': [{u'alternatives': [{u'confidence': 0.987629,
u'transcript': u'how old is the Brooklyn Bridge'}]}]}}