【问题标题】:Get Cloud Storage upload response获取 Cloud Storage 上传响应
【发布时间】:2021-09-30 08:59:03
【问题描述】:

我正在使用 Python SDK 将文件上传到 Cloud Storage 存储分区:

from google.cloud import storage

bucket = storage.Client().get_bucket('mybucket')
df = # pandas df to save
csv = df.to_csv(index=False)
output = 'test.csv'
blob = bucket.blob(output)
blob.upload_from_string(csv)

如何获得响应以了解文件是否已成功上传?我需要记录响应以通知用户该操作。

我试过了:

response = blob.upload_from_string(csv)

但即使操作成功,它也总是返回 None 对象。

【问题讨论】:

  • 如果您使用的是 REST,只需执行 if 循环即可查看 http 返回码是否 == 200。
  • 我试图重现你的代码,但我不太明白你期望哪种类型的响应,你想要作为对象创建的响应还是另一个消息只是提醒用户对象是创建成功了吗?
  • @Vicky 只是一条消息提醒我对象是否创建成功

标签: python google-cloud-storage


【解决方案1】:

您可以尝试使用 tqdm 库。

import os
from google.cloud import storage
from tqdm import tqdm

def upload_function(client, bucket_name, source, dest, content_type=None):
  bucket = client.bucket(bucket_name)
  blob = bucket.blob(dest)
  with open(source, "rb") as in_file:
    total_bytes = os.fstat(in_file.fileno()).st_size
    with tqdm.wrapattr(in_file, "read", total=total_bytes, miniters=1, desc="upload to %s" % bucket_name) as file_obj:
      blob.upload_from_file(file_obj,content_type=content_type,size=total_bytes,
      )
      return blob

if __name__ == "__main__":
  upload_function(storage.Client(), "bucket", "C:\files\", "Cloud:\blob.txt", "text/plain")

【讨论】:

    【解决方案2】:

    关于如何获取有关对存储桶所做更改的通知,您还可以尝试以下几种方法:

    1. 使用 Pub/Sub - 这是 Pub/Sub 通知向 Pub/Sub 发送有关对存储桶中对象的更改的信息的推荐方式,其中信息以以下形式添加到您选择的 Pub/Sub 主题中消息。在这里你会找到一个example using python,就像你的情况一样,并使用gsutil、其他支持的语言或REST APIs等其他方式。

    2. Object change notificationWatchbucket:这将创建一个通知通道,将通知事件发送到给定存储桶 using a gsutil command 的给定应用程序 URL。

    3. 带有Google Cloud Storage Triggers 的Cloud Functions 使用event-driven functions 处理来自Google Cloud Storage 的事件,配置这些通知以响应存储桶内的各种事件(对象创建、删除、归档和元数据更新)进行触发。这里有一些关于如何实现它的documentation

    4. 另一种方法是使用Eventarc 构建event-driven architectures,它提供了一个标准化的解决方案来管理解耦的微服务之间的状态更改流(称为事件)。 Eventarc 将这些事件路由到 Cloud Run,同时为您管理交付、安全、授权、可观察性和错误处理。这里有一个guide关于如何实现它。

    在这里您将能够找到具有相同问题和答案的相关帖子:

    1. 使用Storage-triggered Cloud Function
    2. Object Change Notification and Cloud Pub/Sub Notifications for Cloud Storage
    3. 回复Cloud Pub/Sub topic example

    【讨论】:

      猜你喜欢
      • 2020-04-08
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2021-07-30
      相关资源
      最近更新 更多