获取云存储上载响应

2024-03-28 19:46:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python SDK将文件上载到云存储桶:

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对象


Tags: 文件csvtofromimportclouddfoutput
2条回答

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

  1. 使用Pub/Sub这是推荐的方式,发布/订阅通知将有关对bucket中对象所做更改的信息发送到发布/订阅,并以消息的形式将信息添加到您选择的发布/订阅主题中。在这里,您将找到一个example using python,就像您的例子一样,并使用其他方式,如gsutil、其他支持的语言或REST APIs

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

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

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

在这里,您可以找到具有相同问题和答案的相关帖子:

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

您可以尝试使用TQM库

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")

相关问题 更多 >