我已经设置了云存储存储桶、云发布/订阅主题和订阅,以便在文件上传到存储桶时创建通知。
我想在服务器上创建一个脚本,在新镜像上传到存储桶时订阅消息,并在本地将镜像下载到服务器。我不知道该怎么做--有没有人能给我提供正确方向的资源或指针?
发布于 2019-07-24 01:01:57
答案是几件事情的组合。我必须做的事情的要点可以在这些方法中找到:
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]https://stackoverflow.com/questions/57153082
复制相似问题