如何使用凭据初始化 Google Cloud Storage

2 python google-cloud-storage google-cloud-platform

我可以从文件中执行以下操作:

from google.cloud import storage
self.client = storage.Client.from_service_account_json('/Users/david/file-163219.json')
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试直接传递凭据,则会收到错误消息:

credentials_dict = {
      "type": "service_account",
      "project_id": "asdf-163219",
      "private_key_id": "asdf2938492837498234",
}
credentials = service_account.Credentials.from_service_account_info(credentials_dict)
self.client = storage.Client(credentials=credentials)
Run Code Online (Sandbox Code Playgroud)

但后来我收到一个错误:

google.auth.exceptions.DefaultCredentialsError:无法自动确定凭据。请设置 GOOGLE_APPLICATION_CREDENTIALS 或明确创建凭据并重新运行应用程序。有关更多信息,请参阅https://developers.google.com/accounts/docs/application-default-credentials

传递凭据字典的正确方法是什么?

小智 9

在显式设置客户端凭据时,它需要在创建存储客户端时传递客户端代表的项目。如果未通过,则回退到从环境推断的默认值。

from google.cloud import storage
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_info(credentials_dict)
client = storage.Client(project='project_id', credentials=credentials)
Run Code Online (Sandbox Code Playgroud)


F10*_*F10 5

由于该方法from_service_account_file需要路径,因此您可以使用临时文件。例如:

#!/usr/bin/env python
from google.cloud import storage
from google.oauth2 import service_account
import json
import os
import tempfile
if __name__ == '__main__':
    jsonfile = u"""<HERE GOES THE CONTENT OF YOUR KEY JSON FILE.
    CONSIDER THAT THERE ARE BACKSLASHES WITHIN THE PRIVATE KEY
    THEREFORE USE AN EXTRA BACKSLASH. FOR INSTANCE: 
    -----BEGIN PRIVATE KEY-----\\nSomeRandomText
    INSTEAD OF: 
    -----BEGIN PRIVATE KEY-----\nSomeRandomText"""
    fd, path = tempfile.mkstemp()
    try:
        with os.fdopen(fd, 'w') as tmp:
            tmp.write(jsonfile)
        credentials = service_account.Credentials.from_service_account_file(path)
        storage_client = storage.Client(credentials=credentials)
        bucket = storage_client.get_bucket("your-bucket")
        blobs = bucket.list_blobs()
        for blob in blobs:
            print(blob.name)
    finally:
        os.remove(path)
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。

  • 没错,就是这样理解的。我的问题是如何不从文件而是实际上从字典本身来做到这一点。 (2认同)