gpt4 book ai didi

python-3.x - 云函数属性错误 : 'bytes' object has no attribute 'get' when reading json file from cloud storage

转载 作者:行者123 更新时间:2023-12-04 10:36:33 27 4
gpt4 key购买 nike

我正在尝试从 Google Cloud Storage 读取 JSON key 文件以进行身份​​验证。我有以下功能:

storage_client = storage.Client()
bucket_name = 'bucket_name'
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.get_blob('key.json')
json_data_string = blob.download_as_string()

credentials = ServiceAccountCredentials.from_json_keyfile_dict(
json_data_string,
scopes=['https://www.googleapis.com/auth/analytics',
'https://www.googleapis.com/auth/analytics.edit'])

和以下错误: AttributeError: 'bytes' object has no attribute 'get'
我应该如何阅读/格式化我的 key.json文件以与 ServiceAccountCredentials 一起使用

最佳答案

download_as_string()函数返回字节,但 from_json_keyfile_dict()期待 dict .您需要首先解码字节以将其转换为字符串:

json_data_string = blob.download_as_string().decode('utf8')

然后将此字符串加载为 dict :
import json
json_data_dict = json.loads(json_data_string)

然后你可以调用:
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
json_data_dict,
scopes=['https://www.googleapis.com/auth/analytics',
'https://www.googleapis.com/auth/analytics.edit'])

关于python-3.x - 云函数属性错误 : 'bytes' object has no attribute 'get' when reading json file from cloud storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60156335/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com