Cloud function attribute error: 'bytes' object has no attribute 'get' when reading json file from cloud storage

Cloud function attribute error: 'bytes' object has no attribute 'get' when reading json file from cloud storage

我正在尝试从 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' object has no attribute 'get'

我应该如何 read/format 我的 key.json 文件与 ServiceAccountCredentials

一起使用

download_as_string() 函数 returns 字节,但 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'])