Connect MongoDB with python error, SSL Certification

I stored crypto trade history in MongoDB and tried to run backtest logic based on MongoDB data.

My backtest codes are written in Python and there are some errors that I’m struggling with.

import certifi

ca = certifi.where()
mongo_connet = "mongodb+srv://~~~~@~~~~~~/?retryWrites=true&w=majority"
conn = MongoClient(mongo_connet,tlsCAFile=certifi.where())

The codes start like this. And errors are below.

  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pymongo/cursor.py", line 1264, in next
    if len(self.__data) or self._refresh():
                           ^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pymongo/cursor.py", line 1155, in _refresh
    self.__session = self.__collection.database.client._ensure_session()
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pymongo/mongo_client.py", line 1823, in _ensure_session
    return self.__start_session(True, causal_consistency=False)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pymongo/mongo_client.py", line 1766, in __start_session
    self._topology._check_implicit_session_support()
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pymongo/topology.py", line 573, in _check_implicit_session_support
    self._check_session_support()
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pymongo/topology.py", line 589, in _check_session_support
    self._select_servers_loop(
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pymongo/topology.py", line 259, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: ~~~.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)

Can you tell me what’s the problem and how to fix this??

Hi @bestzion, there is documentation about TLS and PyMongo here.

I would also recommend taking a look at our Which certificate authority signs MongoDB Atlas cluster TLS certificates? documentation, and Common SSL Issues on Python and How to Fix it .

In case the issue persists, please feel free to reach out.