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

GCP虚拟机调用Google Sheets API遇ValueError:客户端凭据类型错误

问题描述

在Google Cloud虚拟机上操作Google Sheet时,因OOB授权流程失效,按照Google Sheets API Python快速启动文档修改代码后,运行报错:

ValueError: Client secrets must be for a web or installed app.

当前已创建「Web application」类型的OAuth 2.0客户端ID,不确定是否符合要求。

使用的核心代码片段:

scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds = None       
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', scopes)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            credentials_path, scopes)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.json', 'w') as token:
        token.write(creds.to_json())
#Store creds in object
my_creds = creds
#Create service
build('sheets', 'v4', credentials=my_creds)
解决方案
  • 修正OAuth客户端ID类型:代码中使用的InstalledAppFlow是针对桌面/安装型应用的授权流程,你创建的「Web application」类型不匹配,导致报错。需要重新创建客户端ID:

    1. 进入Google Cloud控制台的「API和服务」→「凭据」页面
    2. 点击「创建凭据」→「OAuth客户端ID」
    3. 应用类型选择「桌面应用」(Desktop app)
    4. 创建完成后下载JSON格式的客户端密钥文件,替换代码中credentials_path指向的文件
  • 适配虚拟机无界面环境:虚拟机没有本地浏览器,原代码中的run_local_server(port=0)无法正常触发授权流程,需替换为控制台授权方式:
    将代码中的creds = flow.run_local_server(port=0)修改为:

    creds = flow.run_console()
    

    运行代码时,控制台会输出一个授权URL,在本地机器打开该URL,登录授权后获取验证码,将验证码输入到虚拟机的控制台中,完成授权。授权成功后会自动生成token.json,后续运行无需重复授权。

  • 验证文件路径:确保客户端密钥JSON文件的路径正确,文件名无拼写错误,且代码中credentials_path指向该文件的准确位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:15:55