如何使用服务账号凭据向Google Drive上传文件
使用Google服务账号凭据上传文件到Google Drive的完整实现方案
我帮你把代码补全并修正了语法问题,同时整理了完整的实现步骤,这样你就能顺利用服务账号上传文件到Google Drive了:
1. 先安装必要依赖
首先得把需要的Python包装上,打开终端跑这个命令:
pip install google-api-python-client oauth2client
2. 修正并补全后的完整代码
你原来的代码有语法错误(比如from_json_keyfile_name后面缺了括号),我已经补上了,还完善了上传逻辑,包括文件元数据设置、可恢复上传的进度处理:
import os from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials from googleapiclient.http import MediaFileUpload # 替换成你自己的settings模块导入方式 from your_settings_module import settings def upload_file_to_drive(tmp_file_path, tmp_file): # 用服务账号凭据初始化Drive服务 credentials = ServiceAccountCredentials.from_json_keyfile_name( os.path.join(settings.CLIENT_PATH, settings.CLIENT_SECRET_FILE), scopes=settings.SCOPES ) google_drive_service = build('drive', 'v3', credentials=credentials) # 设置上传文件的元数据(比如文件名、目标文件夹) file_metadata = { 'name': tmp_file.name, # 可以改成你想要的自定义文件名 # 如果要上传到指定文件夹,取消下面注释,替换成你的文件夹ID # 注意:必须先把这个文件夹共享给服务账号的邮箱(凭据JSON里的client_email字段) # 'parents': ['你的目标文件夹ID'] } # 初始化媒体上传对象,开启可恢复上传(适合大文件) media = MediaFileUpload( tmp_file_path, mimetype=tmp_file.content_type, resumable=True ) # 创建上传请求 request = google_drive_service.files().create( body=file_metadata, media_body=media, fields='id' # 指定返回上传后的文件ID ) # 处理可恢复上传的进度更新 response = None while response is None: status, response = request.next_chunk() if status: print(f"上传进度: {int(status.progress() * 100)}%") print(f"文件上传完成!文件ID: {response.get('id')}") return response.get('id')
3. 必须注意的几个关键点
- 服务账号权限问题:服务账号有自己独立的Drive空间,如果你想上传到你个人Drive里的文件夹,一定要把目标文件夹共享给服务账号的邮箱(在你下载的JSON凭据文件里找
client_email字段),权限设为「编辑」,不然上传会失败。 - Scopes配置:确保
settings.SCOPES里的权限是对的,比如用['https://www.googleapis.com/auth/drive.file']就够(仅允许上传文件),如果需要全Drive权限可以用['https://www.googleapis.com/auth/drive'],按需选择。 - 可恢复上传:开启
resumable=True后,就算上传中途断网,重新运行代码也能从断点续传,适合大文件上传场景。
内容的提问来源于stack exchange,提问作者Snipper03
相关产品推荐
相关产品推荐

