解决pymongo连接数据库报错certificate verify failed:certificate has expired
作者:果光
问题
使用 pymongo.MongoClient 建立连接时报错
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired
之前遇到过一次这个错误,解决掉之后今天又遇到一次,记录一下。
具体的报错内容:
pymongo.errors.ServerSelectionTimeoutError:
xxxxxx.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),
xxxxxx.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),
xxxxxx.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),
Timeout: 30s,
Topology Description: <TopologyDescription id: 631d41e5181176036e30eacc, topology_type: ReplicaSetNoPrimary, servers: [
<ServerDescription ('xxxxxx.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('xxxxxx.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')>,
<ServerDescription ('xxxxxx.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('xxxxxx.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')>,
<ServerDescription ('xxxxxx.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('xxxxxx.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')>
]>
解决
1.安装 certifi:
pip install certifi
2.连接时加入 tlsCAFile 参数:
import certifi client = pymongo.MongoClient( f"mongodb+srv://{db_username}:{db_password}@{db_host}/?retryWrites=true&w=majority", server_api=ServerApi('1'), tlsCAFile=certifi.where() )
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。