问题
使用 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)')>
]>
解决
- 安装 certifi:
pip install certifi
- 连接时加入 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()
)