繁体   English   中英

如何使用 Python 库轮询 Google 长时间运行的操作?

[英]How do I poll Google Long-Running Operations using Python Library?

我有一个google.api_core.operation.Operation object 来自

operation = client.async_batch_annotate_files(requests=[async_request])

我想检查该操作的状态。 我正在尝试使用google.api_core.operations_v1.AbstractOperationsClient 它有方法get_operation ,它应该返回状态。

client=AbstractOperationsClient()
res=client.get_operation(operation.operation.name)

运行时出现错误:

ValueError: Request {'name': '*redacted*'} does not match any URL path template in available HttpRule's ['/v1/{name=operations/**}']

我相信错误是由这段代码产生的。

我可以开始工作的是使用由 Vision API ImageAnnotatorClient实现和公开的OperationsClient (类似于另一个线程中的这个答案):

ops_client = vision_v1.ImageAnnotatorClient().transport.operations_client

使用此客户端在传递完整的操作名称时有效,这会为您提供有关 URL 模板的初始错误:

ops_client.get_operation(vision_operation.operation.name)

查询get_operation()可为您提供操作的预期元数据,例如用于检测操作何时完成的done状态:

ops_client.get_operation(vision_operation.operation.name).done
# Output
False

否则,如果您需要一种更简单的查询状态的方法,Vision API Operation object 的running()方法会根据完成状态返回简单的TrueFalse 您不必以这种方式实例化OperationsClient

vision_operation.running()

完整片段(基于指南):

def main():
    input_image_uri="gs://cloud-samples-data/vision/label/wakeupcat.jpg"
    output_uri=<destination_bucket>

    ops_client = vision_v1.ImageAnnotatorClient().transport.operations_client

    # get_vision_op() not included for simplicity, returns the Operation out of async_batch_annotate_images() as shown on the linked guide
    vision_operation = get_vision_op(input_image_uri, output_uri)

    print(ops_client.get_operation(vision_operation.operation.name).done)
    print(vision_operation.running())

    print("Waiting for operation to complete...")
    response = vision_operation.result(90)

    print(vision_operation.running())
    print(ops_client.get_operation(vision_operation.operation.name).done)
    # Output sent to destination bucket
    gcs_output_uri = response.output_config.gcs_destination.uri
    print("Output written to GCS")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM