Python 3.x 云函数属性错误:';字节';对象没有属性';获取';从云存储读取json文件时

Python 3.x 云函数属性错误:';字节';对象没有属性';获取';从云存储读取json文件时,python-3.x,google-cloud-platform,google-cloud-functions,google-cloud-storage,service-accounts,Python 3.x,Google Cloud Platform,Google Cloud Functions,Google Cloud Storage,Service Accounts,我正在尝试从Google云存储中读取JSON密钥文件以进行身份验证。我有以下功能: 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 = Ser

我正在尝试从Google云存储中读取JSON密钥文件以进行身份验证。我有以下功能:

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”对象没有属性“get”


我应该如何读取/格式化我的
key.json
文件以与
ServiceAccountCredentials
一起使用
download\u as\u string()
函数返回字节,但
from\u json\u keyfile\u 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'])

字节到底是什么?有没有办法以正确的格式从存储器直接访问json文件?请参阅。“正确的格式”在这里是主观的,云存储只存储二进制blob,所以由您将其转换为您期望的格式。因此,无论我从云存储中提取什么,它都将始终是二进制blob。