You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用字典形式的ServiceAccount访问Google Storage(无需JSON文件)

直接使用字典形式的服务账号访问Google Cloud Storage

错误原因

你误用了方法:from_service_account_json() 要求传入JSON文件的路径字符串,而非字典对象,因此触发类型错误。

正确实现方法

Google Cloud Python SDK 提供了from_service_account_info()方法,可直接接收字典格式的服务账号信息,无需写入JSON文件。

方法一:直接用from_service_account_info创建客户端

from google.cloud import storage
import json

# 你的服务账号字典
service_account = {
  "type": "service_account",
  "project_id": "project_id",
  "private_key_id": "private_key_id",
  "private_key":  "PRIVATE KEY",
  "client_email": "email",
  "client_id": "111111",
  "auth_uri": "https://auth.com",
  "token_uri": "https://token.com",
  "auth_provider_x509_cert_url": "https://certs.com",
  "client_x509_cert_url": "https://www.cert.com"
}

# 创建Storage客户端
storage_client = storage.Client.from_service_account_info(service_account)

# 后续操作保持不变
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
file_data = json.loads(blob.download_as_string())

方法二:先构建Credentials对象再初始化客户端

如果需要自定义认证参数(比如指定授权作用域),可以先创建Credentials对象:

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

service_account = {
  # 你的服务账号字典内容
}

# 可选:指定所需的授权作用域
scopes = ["https://www.googleapis.com/auth/cloud-platform"]
credentials = Credentials.from_service_account_info(service_account, scopes=scopes)

# 用Credentials初始化客户端
storage_client = storage.Client(credentials=credentials, project=service_account["project_id"])

# 后续操作
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
file_data = json.loads(blob.download_as_string())

内容的提问来源于stack exchange,提问作者merkle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:55:23