【问题标题】:How to rename a file while storing it to a GCS bucket如何在将文件存储到 GCS 存储桶时重命名文件
【发布时间】:2020-01-24 02:35:11
【问题描述】:

我正在从 directory.post 验证中读取一个文件,我需要上传一个附加时间戳的文件。

如何在将文件上传到 GCS 存储桶时重命名文件?

我正在使用 Google Storage 客户端。我看到对于 S3,boto 客户端有一种方法,我们可以传递 upload_name= 参数,但我在 GCS 中没有看到类似的方法。

【问题讨论】:

    标签: python-2.7 amazon-s3 google-cloud-platform cloud


    【解决方案1】:

    您可以使用 rename_blob 来获得相同的结果。

    from google.cloud import storage
    
    storage_client = storage.Client() 
    bucket = storage_client.get_bucket("mybucket")
    blob = bucket.blob("myfile")
    blob.upload_from_filename("mynewfile")
    bucket.rename_blob(blob, "mynewfile")
    

    另一种选择是使用rest API,您可以只传递名称参数。

    【讨论】:

      【解决方案2】:

      如果您想重命名存储桶中的现有文件。

      def rename_blob(bucket_name, blob_name, new_blob_name):
          """
          Function for renaming file in a bucket buckets.
      
          inputs
          -----
          bucket_name: name of bucket
          blob_name: str, name of file 
              ex. 'data/some_location/file_name'
          new_blob_name: str, name of file in new directory in target bucket 
              ex. 'data/destination/file_name'
          """
          storage_client = storage.Client.from_service_account_json('creds.json')
      
          bucket = storage_client.bucket(bucket_name)
          blob = bucket.blob(blob_name)
          new_blob = bucket.rename_blob(blob, new_blob_name)
          return new_blob.public_url
      

      【讨论】:

        猜你喜欢
        • 2021-10-24
        • 1970-01-01
        • 2020-09-17
        • 1970-01-01
        • 2022-11-04
        • 1970-01-01
        • 2022-10-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多