python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > pymongo连接数据库报错certificate verify failed:certificate has expired

解决pymongo连接数据库报错certificate verify failed:certificate has expired

作者:果光

这篇文章主要介绍了解决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()
 )

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文