使用Google Drive Python API可列出共享云端硬盘文件但无法下载
解决服务账号下载共享Google云端硬盘文件时的404错误
问题原因
Google Drive API默认仅在服务账号自身的云端硬盘中检索文件,对于独立共享云端硬盘中的文件,必须显式指定supportsAllDrives=True参数,否则API会返回404错误——即使服务账号已拥有该共享盘的访问权限。你的代码能列出共享盘文件,说明权限没问题,但下载时未添加该参数导致找不到目标文件。
修改方案
在调用files().get()和files().get_media()方法时,添加supportsAllDrives=True参数即可解决问题。
修改后的完整代码
import io from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload _CREDENTIALS_FILE = "path_to_credentials.json" scopes = [ "https://www.googleapis.com/auth/drive.readonly", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive", ] # 加载服务账号凭证 creds = service_account.Credentials.from_service_account_file( _CREDENTIALS_FILE, scopes=scopes ) # 创建Drive API服务实例 service = build("drive", "v3", credentials=creds) save_name = "test_file_delete.me" fileID = "SOME_FILE_ID" # 现在可支持共享云端硬盘文件 # 添加supportsAllDrives=True参数,检索共享盘文件 file = service.files().get(fileId=fileID, supportsAllDrives=True).execute() # 添加supportsAllDrives=True参数,获取共享盘文件的媒体资源 request = service.files().get_media(fileId=file["id"], supportsAllDrives=True) fh = io.FileIO(save_name, "wb") downloader = MediaIoBaseDownload(fh, request) done = False while not done: _, done = downloader.next_chunk()
补充说明
supportsAllDrives=True参数会告知API将共享云端硬盘纳入检索范围,这是处理独立共享盘文件时的必要配置。如果后续涉及其他共享盘文件操作(如更新、删除),同样需要添加该参数。
内容的提问来源于stack exchange,提问作者Luis Pineda
相关产品推荐
相关产品推荐

