如何将Flask获取的File Storage类型文件直接上传至Google Drive
实现方案
你拿到的Flask FileStorage 本身就是标准类文件对象,Google Drive API 支持直接传入类文件对象完成上传,完全不需要落地到本地磁盘,适配GAE的运行限制。
前置准备
- 首先在Google Cloud控制台开启项目的Google Drive API权限
- 给你的GAE默认服务账号(格式为
你的项目ID@appspot.gserviceaccount.com)授予目标Google Drive文件夹的「编辑者」权限:打开Drive目标文件夹,右键点击「共享」,粘贴服务账号邮箱后确认权限配置 - 在项目
requirements.txt中添加依赖:
google-api-python-client==2.99.0 google-auth==2.23.0 google-auth-httplib2==0.1.1
核心上传代码示例
from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseUpload from google.auth import app_engine # GAE环境下直接获取默认服务账号凭证 SCOPES = ['https://www.googleapis.com/auth/drive.file'] credentials = app_engine.Credentials(scopes=SCOPES) drive_service = build('drive', 'v3', credentials=credentials) # 你的目标Google Drive文件夹ID,从文件夹URL末尾获取 TARGET_FOLDER_ID = '替换为你自己的文件夹ID' # 直接用你拿到的FileStorage对象上传 file_upload = request.files['filename'] # 配置文件元数据,指定上传到目标文件夹 file_metadata = { 'name': file_upload.filename, 'parents': [TARGET_FOLDER_ID] } # 直接传入FileStorage对象作为上传内容,mimetype自动从上传文件获取 media = MediaIoBaseUpload( file_upload, mimetype=file_upload.content_type, resumable=True ) # 执行上传 uploaded_file = drive_service.files().create( body=file_metadata, media_body=media, fields='id' ).execute() # 上传完成后可以拿到文件ID print(f'文件上传成功,Drive ID: {uploaded_file.get("id")}')
注意事项
- 如果需要上传到个人账号的Drive,不要忘了给服务账号授予文件夹权限,否则服务账号上传的文件只有服务账号自己能访问
resumable=True适合大文件上传,如果你的上传文件普遍小于5MB,可以去掉该参数提升上传速度- 不需要额外读取
file_upload.read()或者写入本地文件,直接传入对象即可,API会自动处理流读取
内容的提问来源于stack exchange,提问作者santiagoorpi
相关产品推荐
相关产品推荐

