如何解决如何从python函数登录Google Cloud Storage?
我是Google云存储的新手,我尝试设置每天下载一次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
解决方法
您可以使用json文件的路径设置环境变量GOOGLE_APPLICATION_CREDENTIALS
,并通过启动不带参数的存储客户端来验证功能。
client = storage.Client()
* 默认情况下,存储客户端使用环境变量GOOGLE_APPLICATION_CREDENTIALS
这是使用JSON凭据的最简单方法,并且与大多数Google Cloud python库兼容。
,经过更多测试后,我发现我错过了添加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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。