You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyDrive上传文件至Google Drive时遇404错误求助

Flask + PyDrive 上传Google Drive时出现404错误

我正在用Python开发Flask应用,通过PyDrive库调用Google Drive API上传本地文件到Google Drive,授权等流程都正常,但上传时出现以下错误:

pydrive.files.ApiRequestError: <HttpError 404 when requesting None returned "File not found: 2". Details: "[{'domain': 'global', 'reason': 'notFound', 'message': 'File not found: 2', 'locationType': 'other', 'location': 'file'}]">

我的代码如下:

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
if file_ext == ".jpg":
    mimeType = "image/jpeg"
elif file_ext == ".png":
    mimeType = "image/png"
elif file_ext == ".gif":
    mimeType = "image/gif"
elif file_ext == ".mp4":
    mimeType = "video/mp4"
elif file_ext == ".mp3":
    mimeType = "audio/mpeg"
elif file_ext == ".wav":
    mimeType = "audio/wav"
elif file_ext == ".bmp":
    mimeType = "image/bmp"
elif file_ext == ".docx":
    mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
elif file_ext == ".txt":
    mimeType = "text/plain"
elif file_ext == ".MOV":
    mimeType = "video/quicktime"
elif file_ext == ".pdf":
    mimeType = "application/pdf"
file1 = drive.CreateFile({"mimeType": mimeType, "parents": [{"kind": "drive#fileLink", "id": uniqueID}]}) #uniqueID是从数据库的fileID中获取的
file1.SetContentFile(filename)
file1.Upload()

这是我的大学项目,我对Flask和PyDrive经验有限,恳请各位提供帮助!谢谢:)


问题排查与解决方法

  • 核心原因:错误提示File not found: 2说明你传入的uniqueID对应的Google Drive资源不存在,或者当前授权账号没有访问权限。

  • 具体排查步骤:

    1. 验证uniqueID有效性:确认数据库中的fileID是Google Drive文件夹的ID(上传文件需要指定父文件夹ID,不能是文件ID),检查ID是否有拼写错误、字符缺失/多余。
    2. 检查访问权限:用当前授权的Google账号登录Drive,直接访问https://drive.google.com/drive/folders/[uniqueID],如果无法打开,说明账号没有该文件夹的访问权限,需要文件夹所有者给你的账号分配权限。
    3. 简化测试:暂时移除parents参数,直接上传文件到Drive根目录,如果上传成功,就可以确定问题出在uniqueID上。
  • 代码优化建议:
    用字典映射替代冗长的if-elif判断,让代码更简洁易维护:

    mime_type_map = {
        ".jpg": "image/jpeg",
        ".png": "image/png",
        ".gif": "image/gif",
        ".mp4": "video/mp4",
        ".mp3": "audio/mpeg",
        ".wav": "audio/wav",
        ".bmp": "image/bmp",
        ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ".txt": "text/plain",
        ".MOV": "video/quicktime",
        ".pdf": "application/pdf"
    }
    mimeType = mime_type_map.get(file_ext, "application/octet-stream") # 未匹配到类型时用默认二进制类型
    

内容的提问来源于stack exchange,提问作者Adam Rust

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:15:34