Colab调用Google API遇无效请求错误,寻求排查方案
问题分析与解决
出现「无效请求」的错误,通常是代码语法/逻辑错误或OAuth客户端配置不当导致的,以下是具体排查和修复方案:
一、修复代码缩进与逻辑错误
Python对缩进严格敏感,你的代码存在多处缩进错误,会导致语法解析失败或逻辑异常,修正后的代码如下:
!pip install httpx starlette fastapi google-auth-oauthlib google-api-python-client from typing import Optional import os from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these SCOPES, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] def get_authenticated_service(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) 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( '/content/client_secret_99.apps.googleusercontent.com.json', SCOPES ) creds = flow.run_local_server(port=0) with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('drive', 'v3', credentials=creds) return service except HttpError as error: print(f"An error occurred: {error}") return None def list_drive_files(service, orderBy='modifiedByMeTime desc', pageSize=5): results = service.files().list( pageSize=pageSize, orderBy=orderBy, fields="nextPageToken, files(id, name, mimeType)" ).execute() items = results.get('files', []) if not items: print('No files found.') else: print('Files:') for item in items: print(f"{item['name']} ({item['mimeType']})") if __name__ == '__main__': os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' service = get_authenticated_service() if service: list_drive_files(service, orderBy='modifiedByMeTime desc', pageSize=5)
关键修正点:
- 统一缩进为4个空格,修复
flow.run_local_server、try块、list_drive_files内代码的缩进问题 - 添加
if service:判断,避免service为None时调用list_drive_files报错 - 合并pip安装命令,简化依赖安装步骤
二、检查OAuth 2.0客户端ID配置
这是导致「无效请求」的核心原因之一,需确保以下配置正确:
- 客户端类型选择正确:在Google Cloud控制台创建OAuth客户端ID时,必须选择「桌面应用」类型,而非Web应用。Colab是云端运行的桌面式授权场景,桌面应用类型会自动适配
localhost重定向。 - 重定向URI正确配置:在客户端ID的设置页面,添加
http://localhost:8080/(或允许http://localhost/*通配符),run_local_server(port=0)会随机使用localhost端口,通配符可覆盖所有情况。 - 客户端密钥文件完整:确保上传到Colab的
client_secret_*.json是从控制台直接下载的原始文件,未修改任何字段(如client_id、client_secret、redirect_uris)。
三、额外注意事项
- 删除旧的
token.json:如果之前授权失败生成过无效的token.json,请删除后重新运行代码,避免缓存的无效凭证干扰。 - 依赖版本兼容:确保
google-auth-oauthlib和google-api-python-client为最新稳定版,可通过pip install --upgrade google-auth-oauthlib google-api-python-client更新。
内容的提问来源于stack exchange,提问作者Spencer
相关产品推荐
相关产品推荐

