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

Python列表存入MongoDB集群报错:SSL证书验证失败求助

解决MongoDB集群SSL证书验证失败问题

错误原因

出现SSL: CERTIFICATE_VERIFY_FAILED是因为Python环境无法验证MongoDB Atlas集群的SSL证书,通常是本地缺少对应的根证书,或者系统CA证书配置异常。

解决方法

方法1:指定MongoDB Atlas根证书(推荐生产环境使用)

  1. 从MongoDB Atlas控制台获取根证书(在集群连接设置的"Connect with MongoDB Compass"或"Connect your application"页面中找到并下载,保存为mongodb-atlas-cert.pem)
  2. 修改MongoClient初始化代码,添加tlsCAFile参数指向证书文件:
uri = "mongodb+srv://tanviropy:<password>@cluster0.lftvw.mongodb.net/?retryWrites=true&w=majority"
# 加上tlsCAFile参数指向证书路径
client = pymongo.MongoClient(uri, tlsCAFile="./mongodb-atlas-cert.pem")

方法2:临时禁用证书验证(仅测试环境使用)

如果只是测试连接,可临时关闭证书验证,但生产环境绝对不能使用:

uri = "mongodb+srv://tanviropy:<password>@cluster0.lftvw.mongodb.net/?retryWrites=true&w=majority"
client = pymongo.MongoClient(uri, tlsAllowInvalidCertificates=True)

方法3:修复Python环境的CA证书(适用于系统证书缺失情况)

如果是Python环境缺少默认CA证书,可安装certifi库并配置使用:

  1. 安装certifi:
pip install certifi
  1. 在代码中指定CA证书路径:
import certifi

uri = "mongodb+srv://tanviropy:<password>@cluster0.lftvw.mongodb.net/?retryWrites=true&w=majority"
client = pymongo.MongoClient(uri, tlsCAFile=certifi.where())

额外注意事项

  • 确保你的IP已经加入MongoDB Atlas的IP白名单,否则即使证书正常也会连接失败
  • 代码中<password>要替换成实际的数据库密码

内容的提问来源于stack exchange,提问作者Tanvir Yeasin Opy 2011046642

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:12:55