17

因此,我正在尝试使用google-cloud-storagePython 库(https://googlecloudplatform.github.io/google-cloud-python/latest/storage/blob.html)为我的 Google Cloud Storage 对象生成临时的全局可读 URL - 更具体地说Blob.generate_signed_url() 方法。我在命令行 Python 脚本中的 Compute Engine 实例中执行此操作。而且我不断收到以下错误:

AttributeError: you need a private key to sign credentials.the credentials you are currently using <class 'oauth2cl
ient.service_account.ServiceAccountCredentials'> just contains a token. see https://google-cloud-python.readthedocs
.io/en/latest/core/auth.html?highlight=authentication#setting-up-a-service-account for more details.

我知道在 GCE(https://github.com/GoogleCloudPlatform/google-auth-library-python/issues/50)中执行此操作存在问题,但我已按照此处的说明创建了一个新的服务帐户凭据:https://cloud.google.com/storage/docs/access-control/create-signed-urls-program我的 key.json 文件肯定包含一个私钥。我仍然看到那个错误。

这是我的代码:

keyfile = "/path/to/my/key.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile)
expiration = timedelta(3) # valid for 3 days
url = blob.generate_signed_url(expiration, method="GET",
                               credentials=credentials) 

我已经阅读了这里的问题跟踪器https://github.com/GoogleCloudPlatform/google-cloud-python/issues?page=2&q=is%3Aissue+is%3Aopen并且没有任何相关的跳出所以我假设这应该可以工作. 看不到这里出了什么问题。

4

2 回答 2

13

我遇到了同样的问题。最终通过直接从服务帐户 json 启动存储客户端来修复它。

storage_client = storage.Client.from_service_account_json('path_to_service_account_key.json')

我知道我迟到了,但希望这会有所帮助!

于 2018-12-12T18:37:16.463 回答
9

blob.generate_signed_url目前,如果不明确引用凭据,则无法使用。(来源:Google-Cloud-Python 文档)但是,您可以采取一种变通方法,如此处所示其中包括:

signing_credentials = compute_engine.IDTokenCredentials(
    auth_request,
    "",
    service_account_email=credentials.service_account_email
)
signed_url = signed_blob_path.generate_signed_url(
    expires_at_ms,
    credentials=signing_credentials,
    version="v4"
)
于 2019-09-16T20:38:50.107 回答