如何使用凭证初始化Google Cloud Storage [英] How to initialize Google Cloud Storage with credentials

查看:127
本文介绍了如何使用凭证初始化Google Cloud Storage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过文件执行以下操作:

I am able to do the following from a file:

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

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

However, if I try and pass the credentials directly, I get an error:

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)

但是我得到一个错误:

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

传递凭据命令的正确方法是什么?

What would be the correct way to pass the credentials dict?

推荐答案

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

Since the method from_service_account_file requires a path, you could use a temporary file. For instance:

#!/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)

希望有帮助.

这篇关于如何使用凭证初始化Google Cloud Storage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆