如何通过Service Account用Python REST API下载Google Drive文件内容
解决Google Drive API服务账号下载文件的403问题
我来帮你搞定这个服务器端自动下载的问题!你遇到的403错误其实是典型的接口误用问题,咱们一步步拆解解决:
问题根源
你调用的export接口(Drive v3)仅支持Google原生文档类型(比如Google Docs、Sheets、Slides、Forms这些,MIME类型以application/vnd.google-apps.开头)。如果你的文件是普通二进制文件(比如TXT、PDF、图片),用这个接口肯定会返回Export only supports Google Docs.的错误。
而你之前在v2 API里看到的downloadUrl,在v3 API里对应的是两种下载方式,需要根据文件类型来选择:
解决方案:分文件类型处理下载
1. 先判断文件类型
调用Drive v3的files.get接口,获取文件的核心信息:
from googleapiclient.discovery import build from google.oauth2.service_account import Credentials # 初始化服务账号认证 creds = Credentials.from_service_account_file('service-account-key.json', scopes=['https://www.googleapis.com/auth/drive.readonly']) drive_service = build('drive', 'v3', credentials=creds) file_id = '1LWkJmHqv7lHfdd6qLq8ssdJ99BYeP-9axC' file = drive_service.files().get(fileId=file_id, fields='id,name,mimeType,exportLinks').execute() print(f"文件MIME类型: {file['mimeType']}")
2. 针对不同类型选择下载方式
情况A:Google原生文档(比如Docs、Sheets)
这类文件没有直接的二进制内容,需要用export接口转成指定格式下载:
# 比如把Google Docs导出为TXT格式 if 'exportLinks' in file: export_url = file['exportLinks']['text/plain'] response = drive_service._http.request(export_url) if response[0].status == 200: content = response[1].decode('utf-8') print("导出的文档内容:", content) # 保存到文件 with open('exported_file.txt', 'w') as f: f.write(content)
情况B:普通二进制文件(TXT、PDF、图片等)
直接用files.get接口加上alt=media参数下载:
# 普通文件下载 request = drive_service.files().get_media(fileId=file_id) response = request.execute() # 保存文件 with open('downloaded_file.txt', 'wb') as f: f.write(response)
关键权限检查
别忘确认这两点,否则可能还是会报权限错误:
- 文件共享权限:把目标文件共享给服务账号的邮箱(在服务账号JSON密钥里的
client_email字段),至少赋予Viewer权限; - API Scope:确保你请求的scope包含
https://www.googleapis.com/auth/drive.readonly(只读)或者https://www.googleapis.com/auth/drive(读写),权限不够也会导致下载失败。
这样就能实现完全服务器端的自动下载流程,不需要浏览器认证啦!
内容的提问来源于stack exchange,提问作者bala




