繁体   English   中英

如何从 python 函数登录 Google Cloud Storage?

[英]How to log into Google Cloud Storage from a python function?

我是谷歌云存储的新手,我尝试设置一个每天下载一次 blob 的功能。 目前我正在我的 Jupyter Notebook 中工作,但最终,代码将在 Azure 函数中运行。 我正在努力设置将我连接到存储桶的客户端。 我有一个服务帐户凭据 JSON,它使我能够连接到 google。

在本地我找到了一个解决方案:

from google.cloud import storage

client = storage.Client.from_service_account_json('<PATH_TO_SERVICE_ACCOUNT_JSON>')

问题是我没有将 JSON 存储在云中的路径,但我将其存储在密钥保管库中。 我想出了以下解决方案:

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

string_key = get_key_from_key_vault()
service_account_info = json.loads(string_key)
google_credentials = service_account.Credentials.from_service_account_info(
    service_account_info
)
scoped_credentials = google_credentials.with_scopes(
    ['https://www.googleapis.com/auth/cloud-platform.read-only'])
print(type(scoped_credentials))
client = storage.Client(credentials = scoped_credentials)

我不完全确定是否需要scoped_credentials = ...部分,但我只有对存储桶的读取权限。 (如果我跳过该部分,错误保持不变)

当我选择此解决方案时,出现以下错误:

DefaultCredentialsError: Could not automatically determine credentials. Please set 
GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For
 more information, please see https://cloud.google.com/docs/authentication/getting-started

我不知道我做错了什么,因为我认为我已经明确设置了凭据。

最佳P

经过更多测试后,我发现我错过了添加project = None 如果您添加它并使用以下命令来创建它可以工作的客户端:

client = storage.Client(project = None, credentials = scoped_credentials)

感谢您的帮助和思考:-)

(我使用答案部分是因为注释中的代码格式很糟糕)

你能试试这个并告诉我你是否看到打印了 2 个访问令牌?

from google.cloud import storage
import json
from google.oauth2 import service_account
from google.auth.transport import requests as grequests

string_key = get_key_from_key_vault()
service_account_info = json.loads(string_key)

google_credentials = service_account.Credentials.from_service_account_info(
    service_account_info
)
google_credentials.refresh(grequests.Request())
print(google_credentials.token)


scoped_credentials = google_credentials.with_scopes(
    ['https://www.googleapis.com/auth/cloud-platform.read-only'])
scoped_credentials.refresh(grequests.Request())
print(scoped_credentials.token)


您可以使用 json 文件的路径设置环境变量GOOGLE_APPLICATION_CREDENTIALS ,并通过启动不带参数的存储客户端来验证您的功能。

client = storage.Client()

*默认情况下,存储客户端使用环境变量GOOGLE_APPLICATION_CREDENTIALS上的文件路径

这是使用 JSON 凭据的最简单方法,并且与大多数 Google Cloud python 库兼容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM