Google cloud get bucket - 适用于 cli 但不适用于 python

Google cloud get bucket - works with cli but not in python

我被要求与外部 google 存储桶进行集成,我收到了凭据 json,

并在努力做的同时 gsutil ls gs://bucket_name(在使用 creds json 配置自己之后)我收到了有效的响应,当我尝试将文件上传到存储桶时也是如此。

尝试使用 Python3 时,它不起作用:

在使用 google-cloud-storage==1.16.0 时(也尝试了较新的版本),我在做:

project_id = credentials_dict.get("project_id")
credentials = service_account.Credentials.from_service_account_info(credentials_dict)
client = storage.Client(credentials=credentials, project=project_id)

bucket = client.get_bucket(bucket_name)

但是在 get_bucket 行,我得到:

google.api_core.exceptions.Forbidden: 403 GET https://www.googleapis.com/storage/v1/b/BUCKET_NAME?projection=noAcl: USERNAME@PROJECT_ID.iam.gserviceaccount.com does not have storage.buckets.get access to the Google Cloud Storage bucket.

与我集成的外部合作伙伴,说用户设置正确,并证明我 可以 执行 gsutil.

你能帮忙吗?知道可能是什么问题吗?

请关注these steps in order to correctly set up the Cloud Storage Client Library for Python. In general, the Cloud Storage Libraries can use Application default credentials or environment variables for authentication.

请注意,建议使用的方法是设置 authentication using environment variables(即如果您使用 Linux:export GOOGLE_APPLICATION_CREDENTIALS="/path/to/[service-account-credentials].json" 应该有效)并避免使用 service_account.Credentials.from_service_account_info() 方法一共:

from google.cloud import storage

storage_client = storage.Client(project='project-id-where-the-bucket-is')
bucket_name = "your-bucket"
bucket = client.get_bucket(bucket_name)

应该可以正常工作,因为身份验证是由客户端库通过环境变量处理的。

现在,如果您有兴趣明确使用服务帐户而不是使用 service_account.Credentials.from_service_account_info() 方法,您可以通过以下方式直接使用 from_service_account_json() 方法:

from google.cloud import storage

# Explicitly use service account credentials by specifying the private key
# file.
storage_client = storage.Client.from_service_account_json(
    '/[service-account-credentials].json')
bucket_name = "your-bucket"
bucket = client.get_bucket(bucket_name)

查找有关如何向您的应用程序提供凭据的所有相关详细信息here

答案是信誉确实是错误的,但当我尝试在客户端 client.bucket(bucket_name) 而不是 client.get_bucket(bucket_name) 上进行预制时它确实有效。