【问题标题】:Not able to upload_from_filename files into GCP bucket using python script and GCP service account cred无法使用 python 脚本和 GCP 服务帐户凭据将文件上传到 GCP 存储桶
【发布时间】:2019-08-05 05:57:26
【问题描述】:

• 已安装 Python 3.7.2 • 创建 GCP 服务帐户并为其赋予所有者角色,还启用存储 API 并创建云存储桶 • 现在我正在尝试使用 python 脚本将文件上传到 GCP 云存储文件夹,但我不能。但是,通过使用相同的结构,我能够创建新的云存储桶并能够编辑其中的现有文件 • 这里附上了pythonscript

参考使用: https://googleapis.github.io/google-cloud-python/latest/storage/blobs.html https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python

from google.cloud import storage

bucket_name='buckettest'
source_file_name='D:/file.txt'
source_file_name1='D:/jenkins structure.png'
destination_blob_name='test/'

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    client = storage.Client.from_service_account_json('D:\gmailseviceaccount.json')
    bucket = client.create_bucket('bucketcreate')
    bucket = client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_filename(source_file_name) 
    blob.upload_from_filename(source_file_name1)

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))

if __name__ == '__main__':
        upload_blob(bucket_name, source_file_name, destination_blob_name)

【问题讨论】:

  • 你好@Yasho R,欢迎来到 StackOverflow!您的服务帐号授予了哪些角色?让他们运行this command 并使用结果编辑问题。
  • 错误信息是什么(堆栈跟踪)?

标签: python google-cloud-platform cloud storage


【解决方案1】:

我能够运行您的代码并对其进行调试。我将把我使用的内容放在下面并解释我所做的更改。

和你一样,我将我的服务帐户设置为所有者并且能够上传。我建议您在完成测试后遵循至少privileges 的最佳实践。

  1. 我删除了client.create_bucket,因为存储桶是独一无二的,我们不应该硬编码存储桶名称来创建。您可以根据需要提出一个命名约定,但是,为了测试我删除了它。
  2. 我修复了变量destination_blob_name,因为您将它用作要放置文件的文件夹。这不起作用,因为 GCS 不使用文件夹,它只使用文件名。发生的事情是,您实际上是在将 TXT 文件“转换”到名为“test”的文件夹中。为了更好地理解,我建议查看How Sub-directories Work 上的文档。

    from google.cloud import storage
    
    bucket_name='bucket-test-18698335'
    source_file_name='./hello.txt'
    destination_blob_name='test/hello.txt'
    
    def upload_blob(bucket_name, source_file_name, destination_blob_name):
        """Uploads a file to the bucket."""
        client = storage.Client.from_service_account_json('./test.json')
        bucket = client.get_bucket(bucket_name)
        blob = bucket.blob(destination_blob_name)
        blob.upload_from_filename(source_file_name) 
    
        print('File {} uploaded to {}.'.format(
            source_file_name,
            destination_blob_name))
    
    if __name__ == '__main__':
            upload_blob(bucket_name, source_file_name, destination_blob_name)
    

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 2022-06-21
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2020-09-07
    • 2020-01-17
    相关资源
    最近更新 更多