无法使用Python脚本和GCP Service帐户信用来将无法上传_FROM_FILENAME文件上传到GCP存储桶中



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

ref使用:https://googleapis.github.io/google-cloud-python/latest/storage/storage/blobs.htmlhttps://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)

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

和您一样,我将服务帐户作为所有者,并且能够上传。我建议在完成测试时遵循最不特权的最佳实践。

  1. 我删除了 client.create_bucket,因为存储桶是唯一的,我们不应该是要创建的硬编码桶名。您可以为您的需求提出命名约定,但是,我将其删除。
  2. 我修复了变量destination_blob_name,因为您将其用作放置文件的文件夹。这将不起作用,因为GCS不使用文件夹,而仅使用文件名。发生的事情是,您实际上是在"将" TXT文件"转换"到名为'Test'的文件夹中。为了更好地理解,我建议您查看有关子目录如何工作的文档。

    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)
    

最新更新