【问题标题】:Download files from google bucket从谷歌存储桶下载文件
【发布时间】:2019-02-09 08:07:15
【问题描述】:

我在我的 Google 存储桶上下载文件时遇到问题 我关注了这个Google tutorial(使用客户端库和服务帐户)

这是我使用的 Python 代码(来自 google 示例): 导入json 从 httplib2 导入 Http 从 oauth2client.client 导入 SignedJwtAssertionCredentials 从 apiclient.discovery 导入构建

client_email = 'myclientname@myproject.iam.gserviceaccount.com'

json_file = 'resources/Google/myproject-anumber.json' ## <---- JSON provided when i created the service account

cloud_storage_bucket = 'mybucketname'

report_to_download = 'path/to/my/file.zip'


private_key = json.loads(open(json_file).read())['private_key']

credentials = SignedJwtAssertionCredentials(client_email, private_key, 
              'https://www.googleapis.com/auth/devstorage.read_only')

storage = build('storage', 'v1', http=credentials.authorize(Http()))
report = storage.objects().get(bucket = cloud_storage_bucket, object = 
report_to_download).execute()

我以为我必须将“报告”输出到文件,但不,如此处所述,报告只是一个 dict 对象:

https://google-api-client-libraries.appspot.com/documentation/storage/v1beta2/python/latest/storage_v1beta2.objectAccessControls.html#get

然后我尝试使用 selfLink 属性或 mediaLink,但没有成功。 'https://cloud.google.com/storage/docs/json_api/v1/objects/get' 相同 它也返回 ACL

提前谢谢你,

【问题讨论】:

    标签: python api google-cloud-storage storage oauth2client


    【解决方案1】:

    您可以使用code shown here 下载对象。我建议关注this document 安装云存储客户端库并设置身份验证。

    以下是根据上述信息下载对象的 Python 代码示例。

    from google.cloud import storage
    if __name__ == '__main__':
        bucket_name = 'your_bucket'
        source_blob_name = 'your_object'
        destination_file_name = 'local_file'
        #DOWNLOAD
        storage_client = storage.Client()
        bucket = storage_client.get_bucket(bucket_name)
        blob = bucket.blob(source_blob_name)
        blob.download_to_filename(destination_file_name)
        print('Blob {} downloaded to {}.'.format(source_blob_name, destination_file_name))
    

    【讨论】:

    • 这意味着support.google.com/googleplay/android-developer/answer/… 描述的方法被弃用了吗?我不想使用 gsutil
    • 那个get 方法返回对象元数据。如果你想下载一个对象,你应该使用client libraries,我正在用代码示例编辑我的答案,以使用 Python 客户端库下载一个对象。
    • 谢谢,它只是元数据并没有真正写出来!我想我可以下载这个文件再查询一次 api
    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2020-06-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    相关资源
    最近更新 更多