Python应用调用Google Sheets API遇400错误:redirect_uri_mismatch
解决Google Sheets API授权Error 400: redirect_uri_mismatch问题
问题描述
我开发了一个向Google Sheets发送数据的小型Python应用,原本运行正常,未修改代码却突然收到Google授权错误。查询得知测试账号7天后过期,于是生成新OAuth凭据,删除旧凭据及token.pickle文件,现在在Google授权页面提示访问被拒绝,报错Error 400: redirect_uri_mismatch。尝试添加授权页面的URL但无效,之前未配置该URL也能正常运行。
附代码:
import pandas as pd from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow, Flow from google.auth.transport.requests import Request import os import pickle # Google Sheets API scopes SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] # Google Sheet information SAMPLE_SPREADSHEET_ID = '1Q1bO2rZR5iuA7hxxxxxxxxxMenKrW16FMzUZsfw' SAMPLE_RANGE_NAME = 'A1:AA1000' # Adjust this range as needed # Function to save it all def save_to_google_sheets(dataframe,team_100_df, team_200_df, team_totals_df, team_bans_df, spreadsheet_id, range_name): creds = None # The file token.pickle 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.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) 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.json', SCOPES) # Replace with your JSON file creds = flow.run_local_server(port=0) with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) values = dataframe.astype(str).values.tolist() values_team_100_df = team_100_df.astype(str).values.tolist() values_team_200_df = team_200_df.astype(str).values.tolist() values_team_totals_df = team_totals_df.astype(str).values.tolist() values_team_bans_df = team_bans_df.astype(str).values.tolist() # Clear existing values in the specified range service.spreadsheets().values().clear( spreadsheetId=spreadsheet_id, range=range_name, ).execute()
问题根源
新生成的OAuth凭据类型错误,或者重定向URI配置不符合桌面应用授权流程的要求。InstalledAppFlow属于桌面应用授权逻辑,和Web应用的重定向规则不兼容。
解决步骤
- 确认凭据类型:登录Google Cloud控制台,找到项目→API和服务→凭据,确保新生成的OAuth客户端ID类型是**「桌面应用」**。如果选成了Web应用或其他类型,删除后重新创建,类型选桌面应用。
- 配置重定向URI:在桌面应用凭据的编辑页面,添加以下两个重定向URI并保存:
http://localhost/http://localhost:8080/
保存后重新下载credentials.json,替换本地文件。
- 固定授权端口(可选):将代码中
flow.run_local_server(port=0)改为flow.run_local_server(port=8080),固定端口避免随机端口导致的不匹配,此时只需确保控制台配置了http://localhost:8080/即可。 - 清理缓存:彻底删除本地的
token.pickle文件,重新运行脚本完成授权流程。
验证
修改完成后重新运行脚本,应该能正常进入Google授权页面,完成授权后即可恢复向Google Sheets写入数据的功能。
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

