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

如何在Python中使用Google App Engine默认服务账号凭据操作gspread

解决Google App Engine中gspread调用默认服务账号的问题

代码修改

原代码中gspread.service_account()会默认查找本地JSON凭据文件,在GAE环境下无法找到该文件,需改用Google Cloud内置的默认服务账号凭据初始化gspread客户端:

  1. 新增必要导入:
import google.auth
from google.auth.transport.requests import Request
  1. 替换原有的gc = gspread.service_account()代码段:
# 获取GAE默认服务账号凭据,指定所需权限范围
creds, project_id = google.auth.default(scopes=[
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'
])

# 刷新过期凭据(若需要)
if not creds.valid:
    if creds.expired and creds.refresh_token:
        creds.refresh(Request())

# 初始化gspread客户端
gc = gspread.Client(auth=creds)
gc.session.headers.update({'Authorization': f'Bearer {creds.token}'})

权限与API配置

  • 配置服务账号权限:找到GAE默认服务账号邮箱(格式为[你的项目ID]@appspot.gserviceaccount.com,可在Cloud控制台「IAM与管理员」→「服务账号」中查看),将该邮箱添加为目标Google Sheet的共享成员,分配编辑/查看权限(按需选择)。
  • 启用必要API:确保项目已启用Google Sheets API和Google Drive API,可在Cloud控制台「API和服务」→「库」中搜索启用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:25:16