Google Drive API请求权限不足,求助正确Scope配置
问题解决:Google Drive API权限不足(Insufficient Permission)
核心错误原因
你当前使用的Scope是https://www.googleapis.com/auth/documents.readonly,这个Scope仅适用于Google Docs文档内容的只读访问,无法用于调用Google Drive API的files.list接口,这是导致权限错误的直接原因。
修复步骤
1. 替换正确的Scope
将代码中的Scope替换为Drive API对应的只读Scope:
credentials = service_account.Credentials.from_service_account_file( json_key_location, scopes=['https://www.googleapis.com/auth/drive.readonly'] )
如果后续需要修改文件或文件夹权限,可根据需求选择更合适的Scope(遵循最小权限原则):
- 完全读写权限:
https://www.googleapis.com/auth/drive - 仅文件元数据访问:
https://www.googleapis.com/auth/drive.metadata.readonly
2. 确认服务账号权限有效性
再次验证服务账号的共享权限:
- 打开目标Google Drive文件夹,点击「共享」
- 找到JSON凭证文件中
client_email字段对应的邮箱,确认它已被添加到文件夹共享列表,权限至少为「查看者」 - 共享设置生效可能需要几分钟,确认后再重新运行代码
3. 清理凭证缓存(可选)
如果之前运行过旧Scope的代码,部分环境可能会缓存凭证,可删除本地的凭证缓存文件(通常在项目目录或系统临时文件夹中),再重新执行代码。
修改后的完整代码片段
from google.oauth2 import service_account from googleapiclient.discovery import build from dotenv import load_dotenv import os load_dotenv() json_key_location = os.getenv('API_KEY_JSON_PATH') # 使用正确的Drive API只读Scope credentials = service_account.Credentials.from_service_account_file( json_key_location, scopes=['https://www.googleapis.com/auth/drive.readonly'] ) drive_service = build('drive', 'v3', credentials=credentials) folder_name = 'fake-folder-id' results = drive_service.files().list(q=f"name = '{folder_name}' and mimeType = 'application/vnd.google-apps.folder'").execute() folders = results.get('files', []) if folders: folder_id = folders[0]['id'] print(f"The folder ID for '{folder_name}' is: {folder_id}") else: print(f"No folder found with the name '{folder_name}'")
内容的提问来源于stack exchange,提问作者Syllogism
相关产品推荐
相关产品推荐

