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

Python项目连接MongoDB遇SSL证书验证失败问题求助

解决MongoDB Python连接时的SSL证书验证失败问题

这个错误的核心是Python运行环境无法验证MongoDB Atlas集群的SSL证书,通常是因为系统缺少必要的根证书,或者Python的SSL配置没有正确加载证书。下面是几种可行的解决方法:

推荐方案:使用certifi库加载正确的根证书

这是生产环境下的安全做法,步骤如下:

  1. 升级或安装certifi库,它会提供最新的根证书集合:
    pip install --upgrade certifi
    
  2. 修改连接代码,指定证书路径:
    import certifi
    from pymongo import MongoClient
    from pymongo.server_api import ServerApi
    
    uri = "你的MongoDB连接字符串"
    # 加载certifi提供的根证书
    client = MongoClient(uri, server_api=ServerApi('1'), tlsCAFile=certifi.where())
    
    try:
        client.admin.command('ping')
        print("Pinged your deployment. You successfully connected to MongoDB!")
    except Exception as e:
        print(e)
    

临时测试方案:跳过证书验证(仅用于测试环境)

注意:生产环境绝对禁止使用,会带来严重的安全风险
如果只是临时测试连接,可以临时关闭证书验证:

from pymongo import MongoClient
from pymongo.server_api import ServerApi

uri = "你的MongoDB连接字符串"
client = MongoClient(uri, server_api=ServerApi('1'), tlsInsecure=True)

try:
    client.admin.command('ping')
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)

系统层面修复:更新系统根证书

如果上述方法无效,可能是系统本身缺少根证书,根据操作系统执行对应命令:

  • macOS:安装Xcode命令行工具并更新证书
    xcode-select --install
    
  • Debian/Ubuntu Linux:更新系统证书包
    sudo apt-get update && sudo apt-get install --reinstall ca-certificates
    
  • Windows:通过系统设置更新根证书(设置→更新和安全→Windows更新)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 06:55:01