You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

使用Python调用Google Sheets API下载表格时遇401认证错误求助

Google Sheet导出CSV遭遇401认证错误求助

我尝试用Python结合Google认证相关库将Google Sheet导出为CSV文件,但始终碰到401认证错误。

我的代码:

import os
import logging
import requests 
import sys
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build 
from googleapiclient.errors import HttpError

#local defs
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
SPREADSHEET_ID = "<ID>"
OUT_DIR = 'tmp/'
OUT_FILENAME = "locationOfServices.csv"

#Process to download the google sheet 
def getGoogleSeet(spreadsheet_id, outDir, outFile):
  url =  f'https://docs.google.com/spreadsheets/d/<ID>/export?format=csv'
  response = requests.get(url)
  if response.status_code == 200:
      filepath = os.path.join(outDir, outFile)
      with open(filepath, 'wb') as f:
          f.write(response.content)
          print('CSV file saved to: {}'.format(filepath))
  else:
      print(f'Error downloading Google Sheet: {response.status_code}')
      sys.exit()

#Main function to loc ingo Google Sheet 
def main():
    credentials = None
    if os.path.exists("token.json"):
        credentials = Credentials.from_authorized_user_file("token.json", SCOPES)
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            credentials = flow.run_local_server(port=0)
        with open("token.json", "w") as token:
            token.write(credentials.to_json())
    try:
        service = build("sheets", "v4", credentials=credentials)
        sheets = service.spreadsheets()
        
        os.makedirs(OUT_DIR, exist_ok = True)
        filepath = getGoogleSeet(SPREADSHEET_ID, OUT_DIR, OUT_FILENAME)
        
        sys.exit(0); ## success
    except HttpError as error:
        print(error)

if __name__ ==  "__main__": 
    main()

操作情况:

首次运行程序时,我选择服务账号完成授权,成功生成token.json文件,但同时出现401错误。后续多次调整配置仍无法解决问题。

我已确认:

  • 服务账号拥有该Google Sheet的编辑权限
  • 在Google Cloud中创建了项目,启用Google Sheets API并生成OAuth客户端ID
  • 下载的凭证文件已重命名为credentials.json并存放在工作目录中

相关配置截图:

  • 客户端配置
  • 工作目录文件
  • 桌面客户端类型
  • 受众配置
  • 数据访问权限

有人能指出我操作中的错误吗?

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

火山引擎 最新活动