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

切换Google Cloud项目后,Python无法访问新项目的Cloud Storage Bucket

Windows下Python连接Google Cloud Storage Bucket故障排查方案
  • 检查凭据路径与代码配置
    Windows系统中gcloud默认应用凭据路径为%APPDATA%\gcloud\application_default_credentials.json,先确认该文件存在且未损坏。
    可在代码中显式指定凭据路径避免读取异常:

    from google.cloud import storage
    client = storage.Client.from_service_account_json('C:\\Users\\你的用户名\\AppData\\Roaming\\gcloud\\application_default_credentials.json')
    

    或临时设置环境变量后重启Python环境:

    set GOOGLE_APPLICATION_CREDENTIALS=C:\Users\你的用户名\AppData\Roaming\gcloud\application_default_credentials.json
    
  • 验证凭据有效性与网络连通性
    执行gcloud auth application-default print-access-token获取临时令牌,用curl测试API连通性:

    curl -H "Authorization: Bearer 你的令牌内容" https://storage.googleapis.com/storage/v1/b/你的Bucket名称
    

    若curl能正常返回Bucket信息但Python不行,说明Python环境未正确读取系统凭据,检查虚拟环境是否隔离了系统环境变量。

  • 更新依赖库版本
    旧版本的Google Cloud Python库可能存在兼容性问题,执行以下命令升级:

    pip install --upgrade google-cloud-storage google-auth
    

    升级后执行pip show google-cloud-storage确认版本为最新稳定版。

  • 排查系统权限与环境冲突
    确保运行Python的用户拥有%APPDATA%\gcloud目录的读取权限;检查是否存在错误设置的GOOGLE_CLOUD_PROJECT环境变量,导致指向了非目标项目;尝试关闭VPN或代理,部分网络环境会拦截Google API请求。

  • 用最小化代码定位问题
    运行以下简化代码排除业务代码干扰,获取具体错误信息:

    from google.cloud import storage
    
    def test_connection():
        try:
            client = storage.Client()
            buckets = list(client.list_buckets())
            print(f"成功连接,项目下Bucket列表: {[b.name for b in buckets]}")
        except Exception as e:
            print(f"连接失败详情: {str(e)}")
    
    if __name__ == "__main__":
        test_connection()
    

    根据输出的错误提示(如权限不足、项目不存在等)针对性调整配置。

内容的提问来源于stack exchange,提问作者Anthony M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:24:31