首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建一个脚本来检索上传到Google Cloud存储桶的图像

创建一个脚本来检索上传到Google Cloud存储桶的图像
EN

Stack Overflow用户
提问于 2019-07-23 04:08:53
回答 1查看 62关注 0票数 1

我已经设置了云存储存储桶、云发布/订阅主题和订阅,以便在文件上传到存储桶时创建通知。

我想在服务器上创建一个脚本,在新镜像上传到存储桶时订阅消息,并在本地将镜像下载到服务器。我不知道该怎么做--有没有人能给我提供正确方向的资源或指针?

EN

回答 1

Stack Overflow用户

发布于 2019-07-24 01:01:57

答案是几件事情的组合。我必须做的事情的要点可以在这些方法中找到:

代码语言:javascript
复制
from google.cloud import pubsub_v1, storage

def retrieve_image(message):

    attributes = message.attributes

    bucket_id = attributes['bucketId']
    source_blob_name = attributes['objectId']
    destination_file_name = 'images/' + source_blob_name

    download_blob(bucket_id, source_blob_name, destination_file_name)

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(source_blob_name)

    blob.download_to_filename(destination_file_name)

    print('Blob {} downloaded to {}.'.format(
        source_blob_name,
        destination_file_name))

def poll_notifications(project, subscription_name):
    """Polls a Cloud Pub/Sub subscription for new GCS events for display."""
    # [BEGIN poll_notifications]
    subscriber = pubsub_v1.SubscriberClient()
    subscription_path = subscriber.subscription_path(
        project, subscription_name)

    def callback(message):
        print('Received message:\n{}'.format(summarize(message)))
        retrieve_image(message)
        # run_openpose(message)
        message.ack()

    subscriber.subscribe(subscription_path, callback=callback)

    # The subscriber is non-blocking, so we must keep the main thread from
    # exiting to allow it to process messages in the background.
    print('Listening for messages on {}'.format(subscription_path))
    while True:
        time.sleep(60)
    # [END poll_notifications]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57153082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档