Gmail API认证时出现URI不匹配404错误求助
Gmail API认证遇URI不匹配404错误问题
调用以下Python代码中的gmail_authenticate()函数进行Gmail API认证时,出现URI不匹配的404错误。已在Google云控制台添加回调URI,但问题仍未解决。
相关代码
def gmail_authenticate(): 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 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.pickle', 'wb') as token: pickle.dump(creds, token) # Build the Gmail service, Connect to the Gmail API service = build('gmail', 'v1', credentials=creds) return service
Google云控制台配置截图

解决方法
- 纠正OAuth客户端类型:代码中使用
run_local_server(port=0)属于桌面应用认证流程,你当前配置的是网页应用类型的回调URI,两者不兼容。需要在Google云控制台重新创建桌面应用类型的OAuth客户端ID,该类型无需手动填写回调URI,系统会自动适配localhost随机端口。 - 清理旧凭据:删除本地的
token.pickle文件,旧凭据是基于错误的客户端配置生成的,必须清除后重新运行认证流程。 - 替换密钥文件:确保代码中
credentials_path指向新创建的桌面应用对应的credentials.json文件,不要继续使用旧的网页应用密钥文件。
内容的提问来源于stack exchange,提问作者Diana Brook
相关产品推荐
相关产品推荐

