Search code examples
python-3.xmongodbpymongo

PyMongo: [SSL: CERTIFICATE_VERIFY_FAILED]


I am new to MongoDB and am trying to connect to it using Python. I got most this code from the tutorial (i filled in the placeholders):

from pymongo.mongo_client import MongoClient

# Replace the placeholder with your Atlas connection string
uri = "mongodb+srv://<USER NAME>:<USER PASS>@<URL I GOT FROM ATLAS>/?retryWrites=true&w=majority"

# Set the Stable API version when creating a new client
client = MongoClient(uri)

print('created mongo client')

try:
    # Send a ping to confirm a successful connection
    client.admin.command('ping')
except Exception as e:
    print(e)

However, when I try to run it, I get an error. Here is some of it:

ac-teyl7re-shard-00-00.<ATLAS URL>:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:992),
ac-teyl7re-shard-00-02.<ATLAS URL>:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:992),
ac-teyl7re-shard-00-01.<ATLAS URL>:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:992), Timeout: 30s, Topology Description: <TopologyDescription id: 65063bb34951a43c73ce94df, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-teyl7re-shard-00-00.<ATLAS URL>', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-teyl7re-shard-00-00.<ATLAS URL>: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:992)')>, 
<ServerDescription ('ac-teyl7re-shard-00-01.<ATLAS URL>', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-teyl7re-shard-00-01.<ATLAS URL>:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:992)')>, <ServerDescription ('ac-teyl7re-shard-00-02.<ATLAS URL>', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-teyl7re-shard-00-02.<ATLAS URL>:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:992)')>]>

I couldn't find any resources online that were specific to PyMongo.

I am running Python 3.11 and PyMongo 4.5.0


Solution

  • It worked when adding import certifi and changing from MongoClient(uri) to MongoClient(uri, tlsCAFile=certifi.where())