首页 > 解决方案 > 尽管已登录,但无法从 Python 连接到 GCS 存储桶

问题描述

我设置了一个 GCS 存储桶,其中包含我想要远程访问的数据。按照说明,我已通过 登录gcloud auth login,并已通过 确认我有一个有效的凭据帐户gcloud auth list。但是,当我尝试访问我的存储桶(使用 Python google.cloud.storage API)时,我得到以下信息:

HttpError: Anonymous caller does not have storage.objects.list access to <my-bucket-name>.

我不确定为什么要匿名访问它,因为我已经清楚地登录了。我有什么明显的遗漏吗?

标签: google-cloud-storage

解决方案


Python GCP 库(和其他库)使用 gcloud 命令之外的另一种身份验证机制。

按照本指南设置您的环境并使用 Python 访问 GCS。

gcloud aut login使用您的凭据设置gcloud命令工具。

但是,执行代码时的前进方向是拥有一个服务帐户。然后,当 env. 变量 GOOGLE_APPLICATION_CREDENTIALS 已设置。Python 将使用服务帐户凭据

编辑

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path_to_your_.json_credential_file"

编辑

然后,下载gs://my_bucket/my_file.csv到文件:(来自python-docs-samples

download_blob('my_bucket', 'my_file.csv', 'local/path/to/file.csv')
def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    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))

推荐阅读