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

Python打包为exe后调用Google Drive API保存图片报错求助

解决打包exe后Google Drive API报UnknownApiNameOrVersion错误的问题

问题根源

本地运行时,googleapiclient.discovery.build能自动加载或下载Drive API v3的发现文档,但打包成exe(如PyInstaller)时,打包工具默认不会包含这份文档,导致运行时无法识别API的名称和版本,触发该错误。


解决方案

方案一:使用离线发现文档

  1. 获取Drive v3发现文档:从Google API官方渠道获取Drive v3的REST格式发现文档,保存为drive_v3.json,与脚本放在同一目录。
  2. 修改代码,通过本地文档构建服务:
    替换原代码中创建Drive服务的代码块,改为从本地加载发现文档:
    from google.oauth2 import service_account
    from googleapiclient.discovery import build
    from googleapiclient.http import MediaFileUpload
    import json
    
    # 加载本地Drive API发现文档
    with open('drive_v3.json', 'r') as f:
        drive_discovery_doc = json.load(f)
    
    # 加载API密钥
    credentials = service_account.Credentials.from_service_account_file(
        'My_Actual_Json_Key', scopes=['https://www.googleapis.com/auth/drive'])
    
    # 使用本地文档创建Drive服务
    drive_service = build(
        'drive', 
        'v3', 
        credentials=credentials,
        discovery_document=drive_discovery_doc,
        static_discovery=False
    )
    
    # 后续上传代码保持不变
    
  3. 打包时包含drive_v3.json:若用PyInstaller,打包命令添加:
    pyinstaller --add-data "drive_v3.json;." your_script.py
    

方案二:打包时包含API发现文档目录

google-api-python-client的发现文档默认存放在Python环境的site-packages/googleapiclient/discovery_cache/documents目录下,其中包含drive_v3.json。打包时直接将该目录纳入:

  • PyInstaller命令示例(替换路径为你的实际site-packages路径):
    pyinstaller --add-data "C:/Python39/Lib/site-packages/googleapiclient/discovery_cache/documents;googleapiclient/discovery_cache/documents" your_script.py
    

方案三:禁用在线发现服务

在代码最顶部添加环境变量配置,强制使用离线缓存的文档:

import os
os.environ['GOOGLE_API_USE_DISCOVERY_SERVICE'] = '0'

注:此方法需确保本地已存在Drive v3的发现文档缓存,或结合方案一使用。


额外注意事项

  • 打包时需确保API密钥JSON和图片文件被正确包含:例如用PyInstaller的--add-data参数添加:--add-data "My_Actual_Json_Key;." --add-data "Salzburg3.jpg;."
  • 优先用--onedir模式打包测试,比--onefile更易排查文件缺失问题,确认正常后再打包成单文件exe。

内容的提问来源于stack exchange,提问作者Gundyabhau Dandekar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:23:18