📅  最后修改于: 2023-12-03 15:35:08.974000             🧑  作者: Mango
When working with MongoDB Atlas in Python using SSL, you might come across a common error message: SSL: CERTIFICATE_VERIFY_FAILED
. This error occurs because Python does not recognize the SSL certificate presented by the MongoDB Atlas server.
This error can be caused by a variety of reasons, including:
Depending on the cause of the error, there are several solutions to resolve the SSL: CERTIFICATE_VERIFY_FAILED
error when connecting to MongoDB Atlas in Python:
To fix this error caused by outdated root certificate authorities, you can update them using the following steps:
cacert.pem
file.cacert.pem
file to your local system.REQUESTS_CA_BUNDLE
environment variable to the file path of cacert.pem
.Example code for setting the environment variable:
import os
os.environ['REQUESTS_CA_BUNDLE'] = '/path/to/cacert.pem'
If the SSL certificate presented by the MongoDB Atlas server is invalid or expired, you can validate it using the following steps:
If the certificate is valid, try connecting to MongoDB Atlas again.
If the SSL certificate presented by the MongoDB Atlas server is self-signed or signed by an untrusted authority, you can bypass SSL verification using the following steps:
ssl_cert_reqs
parameter to ssl.CERT_NONE
when creating the MongoClient instance.try
and except
block to catch any SSL certificate verification errors.Example code for bypassing SSL verification:
import ssl
from pymongo import MongoClient
# Set ssl_cert_reqs to ssl.CERT_NONE
client = MongoClient('mongodb+srv://<username>:<password>@<cluster>.mongodb.net/test?retryWrites=true&w=majority',
ssl=True, ssl_cert_reqs=ssl.CERT_NONE)
try:
# Use the client to perform operations on the MongoDB Atlas cluster
db_list = client.list_database_names()
except ssl.CertificateError as e:
# Handle any SSL certificate verification errors
print(e)
By using the above solutions, you should now be able to successfully connect to MongoDB Atlas in Python while avoiding the SSL: CERTIFICATE_VERIFY_FAILED
error. It is important to keep your SSL certificates up to date and be aware of any SSL certificate verification errors.