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

使用Python连接Google Sheets时如何导入线上存储的JSON密钥文件

问题解决方法

错误原因

ServiceAccountCredentials.from_json_keyfile_name() 仅支持读取本地文件系统路径,不支持直接传入HTTP/HTTPS类型的线上资源链接,这是报错的核心原因。

可行解决方案

方案1:拉取线上密钥内容后直接生成凭证(无需落地本地文件)

你可以先通过对应平台的API拉取密钥的JSON内容,再使用from_json_keyfile_dict()方法直接生成凭证,不需要把密钥存到本地。
以Slack托管的密钥为例,代码示例如下:

import requests
import json
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
# Slack私有文件请求需要带授权头,Token可在Slack开发者平台生成
headers = {"Authorization": "Bearer 你的Slack授权Token"}
resp = requests.get("你的Slack密钥文件链接", headers=headers)
key_dict = json.loads(resp.text)
credentials = ServiceAccountCredentials.from_json_keyfile_dict(key_dict, scope)

方案2:使用环境变量存储密钥内容(更适合组织内共用)

该方案无需依赖线上文件存储,安全性和稳定性更高,操作步骤如下:

  1. 将你的JSON密钥文件内容压缩为单行字符串
  2. 组织内所有成员在本地系统中配置名为GOOGLE_SHEETS_CREDS的环境变量,值为上述单行字符串
  3. 统一使用如下代码读取凭证:
import os
import json
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds_content = os.getenv("GOOGLE_SHEETS_CREDS")
creds_dict = json.loads(creds_content)
credentials = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)

注意事项

  • Slack/Google Drive的私有文件链接默认需要身份验证,不要直接将明文链接硬编码在代码中
  • 密钥属于敏感信息,禁止提交到公共代码仓库
  • 若选择方案1,需要确保所有组织成员的设备都有对应线上平台的访问权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:48:00