结构化数据文件不会立即生成。Display & Video 360 可能需要几秒到几小时的时间来生成 SDF。
如需确定任务是否已完成,请定期使用 sdfdownloadtasks.operations.get 检索操作,并检查 done 字段是否为 True,以及任务是否已完成。此过程称为“轮询”。
如果任务已完成,则会设置 response 或 error 字段。如果 error 字段已填充,则表示任务失败,并且结果 Status 对象中提供了有关失败的详细信息。如果 response 字段已填充,则表示 Display & Video 360 已成功生成 SDF。从 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))