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

使用JSON API密钥的OAuth2服务账号调用Drive API代码报错求助

排查Google Sheets API服务账号认证异常的问题

从你的代码片段和报错场景来看,主要有几个核心问题需要逐一修正,我帮你梳理下解决步骤:

1. 错误的API作用域(Scope)

你当前设置的scope = ['https://spreadsheets.google.com/spreadsheets']不是Google Sheets API的合法作用域,正确的作用域应该是以下二者之一:

  • 读写权限:https://www.googleapis.com/auth/spreadsheets
  • 只读权限:https://www.googleapis.com/auth/spreadsheets.readonly

修正后的作用域代码:

scope = ['https://www.googleapis.com/auth/spreadsheets']

2. ServiceAccountCredentials方法调用错误

ServiceAccountCredentials.from_json()方法要求传入的是JSON格式的字符串内容,而不是本地JSON密钥文件的文件名。如果你要读取本地的密钥文件,应该改用from_json_keyfile_name()方法:

from oauth2client.service_account import ServiceAccountCredentials
import gspread

# 修正作用域
scope = ['https://www.googleapis.com/auth/spreadsheets']
# 读取本地密钥文件(注意替换成你的实际文件名,比如client_secret.json)
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

3. 额外的必要检查项

  • 确认密钥文件路径正确:如果文件不在脚本当前工作目录,需要传入完整路径(比如'C:/Users/Will Kaiser\'s PC/Documents/PyCharm/Projects/ph/client_secret.json')
  • 给服务账号授权:把JSON密钥文件里client_email字段对应的邮箱,添加到目标Google表格的共享列表中,并赋予编辑/查看权限
  • 启用对应API:确保在Google Cloud Console里已经开启了Google Sheets API(如果操作表格的话,Drive API不是必需的)

如果按上述步骤修改后仍有报错,可以把完整的异常信息贴出来,这样能更精准定位问题~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:09:31