結構化資料檔案不會立即產生,Display & Video 360 可能需要幾秒到幾小時才能產生結構化資料檔案。
如要判斷工作是否完成,請定期使用 sdfdownloadtasks.operations.get 擷取作業,並檢查 done 欄位是否為 True,以及工作是否完成。這個程序稱為「輪詢」。
如果工作已完成,系統會設定 response 或 error 欄位。如果 error 欄位已填入資料,表示工作失敗,且失敗詳細資料會顯示在產生的 Status 物件中。如果「response」欄位已填入資料,表示 Display & Video 360 已成功產生結構化資料檔案。從 response.resourceName 中提供的位置下載產生的檔案。
如果輪詢實作項目效率不彰,檢查長時間執行的報表時,會耗用大量 API 請求配額。如要限制重試次數並節省配額,請使用指數輪詢。
以下是如何使用指數退避演算法輪詢 SDF 下載操作:
# Provide the name of the sdfdownloadtask operation. operation_name = operation-name # Set the following values that control retry behavior while the operation # is running. # Minimum amount of time between polling requests. Defaults to 5 seconds. min_retry_interval = 5 # Maximum amount of time between polling requests. Defaults to 5 minutes. max_retry_interval = 5 * 60 # Maximum amount of time to spend polling. Defaults to 5 hours. max_retry_elapsed_time = 5 * 60 * 60 # Configure the sdfdownloadtasks.operations.get request. get_request = service.sdfdownloadtasks().operations().get(operation_name) sleep = 0 start_time = time.time() while True: # Get current status of the report. operation = get_request.execute() if "done" in operation: if "error" in operation: print( f'The operation finished in error with code ' f'{operation["error"]["code"]}: {operation["error"]["message"]}') else: print( f'The operation completed successfully. The resulting files can be ' f'downloaded at {operation["response"]["resourceName"]}.') break elif time.time() - start_time > max_retry_elapsed_time: print("SDF generation deadline exceeded.") break sleep = next_sleep_interval(sleep) print( f'Operation {operation_name} is still running, sleeping for ' f'{sleep} seconds.') time.sleep(sleep) def next_sleep_interval(previous_sleep_interval): """Calculates the next sleep interval based on the previous.""" min_interval = previous_sleep_interval or min_retry_interval max_interval = previous_sleep_interval * 3 or min_retry_interval return min(max_retry_interval, random.randint(min_interval, max_interval))