Blob.generate_signed_url()未能成为AttributeError

时间:2017-10-03 09:02:48

标签: python google-cloud-storage google-compute-engine google-cloud-python

所以我正在尝试使用google-cloud-storage Python库(https://googlecloudplatform.github.io/google-cloud-python/latest/storage/blobs.html)为我的Google云端存储对象生成临时的全局可读网址 - 更具体地说是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并没有任何相关内容跳出来,所以我认为这应该可行。看不出这里出了什么问题。

2 个答案:

答案 0 :(得分:1)

当前,如果不显式引用凭据,则无法使用blob.generate_signed_url。 (来源:Google-Cloud-Python documentation)但是,您可以采取一种解决方法,如here所示,该解决方法包括:

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")

答案 1 :(得分:0)

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

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

我知道我参加聚会迟到了,但希望对您有帮助!