ServerSelectionTimeoutError with PyMongo and Flask

I keep getting this error when running my app:

ServerSelectionTimeoutError
pymongo.errors.ServerSelectionTimeoutError: ac-44cplg1-shard-00-00.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992),ac-44cplg1-shard-00-01.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992),ac-44cplg1-shard-00-02.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992), Timeout: 30s, Topology Description: <TopologyDescription id: 6458fac66937013406d9805d, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-44cplg1-shard-00-00.hpw8h6y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-44cplg1-shard-00-00.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)')>, <ServerDescription ('ac-44cplg1-shard-00-01.hpw8h6y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-44cplg1-shard-00-01.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)')>, <ServerDescription ('ac-44cplg1-shard-00-02.hpw8h6y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-44cplg1-shard-00-02.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)')>]>

Traceback (most recent call last)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/flask/app.py", line 2486, in __call__
return self.wsgi_app(environ, start_response)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/flask/app.py", line 2466, in wsgi_app
response = self.handle_exception(e)
           ^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/flask/app.py", line 2463, in wsgi_app
response = self.full_dispatch_request()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/flask/app.py", line 1760, in full_dispatch_request
rv = self.handle_user_exception(e)
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/flask/app.py", line 1758, in full_dispatch_request
rv = self.dispatch_request()
     ^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/flask/app.py", line 1734, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kelly/Desktop/argonne/git lab repos/savvyshopper/frontend/src/app.py", line 13, in index
return render_template('index.html', data = data)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/flask/templating.py", line 147, in render_template
return _render(app, template, context)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/flask/templating.py", line 130, in _render
rv = template.render(context)
     ^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/jinja2/environment.py", line 1304, in render
self.environment.handle_exception()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/jinja2/environment.py", line 925, in handle_exception
raise rewrite_traceback_stack(source=source)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kelly/Desktop/argonne/git lab repos/savvyshopper/frontend/src/templates/index.html", line 53, in <module>
{% for row in data %}
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pymongo/cursor.py", line 1248, in next
if len(self.__data) or self._refresh():
                       ^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pymongo/cursor.py", line 1139, in _refresh
self.__session = self.__collection.database.client._ensure_session()
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pymongo/mongo_client.py", line 1712, in _ensure_session
return self.__start_session(True, causal_consistency=False)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pymongo/mongo_client.py", line 1657, in __start_session
self._topology._check_implicit_session_support()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pymongo/topology.py", line 538, in _check_implicit_session_support
self._check_session_support()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pymongo/topology.py", line 554, in _check_session_support
self._select_servers_loop(
^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pymongo/topology.py", line 238, in _select_servers_loop
raise ServerSelectionTimeoutError(
^
pymongo.errors.ServerSelectionTimeoutError: ac-44cplg1-shard-00-00.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992),ac-44cplg1-shard-00-01.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992),ac-44cplg1-shard-00-02.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992), Timeout: 30s, Topology Description: <TopologyDescription id: 6458fac66937013406d9805d, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-44cplg1-shard-00-00.hpw8h6y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-44cplg1-shard-00-00.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)')>, <ServerDescription ('ac-44cplg1-shard-00-01.hpw8h6y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-44cplg1-shard-00-01.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)')>, <ServerDescription ('ac-44cplg1-shard-00-02.hpw8h6y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-44cplg1-shard-00-02.hpw8h6y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)')>]>
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

Here is my code:

from flask import Flask, render_template
from flask_pymongo import PyMongo

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb+srv://<hidingusernameforpost>:<hidingpwdforpost>@cluster0.hpw8h6y.mongodb.net/dbName"

mongo = PyMongo(app)

@app.route("/")
def index():
    collection = mongo.db.dbName
    data = collection.find()
    return render_template('index.html', data = data)


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8005, debug=True)  # nosec

Things I’ve tried:

  • Instructions from similar topics

  • Connecting to my db successfully through atlas

  • Connecting to it successfully via vscode mongodb plugin

  • Utilizing ?ssl=true, ?ssl=true&ssl_cert_reqs=CERT_NONE, ssl=true&ssl_ca_certs=/path/to/ca.pem, in the trailing uri

Thank you in advance for helping me. I know discourse support is not easy :pray: :pray:

Hi @Kelly_Moreira, which versions of PyMongo and Python are you using?

Hi @Steve_Silvester,

Thanks so much for helping me!

Python 3.11.2
PyMongo 4.2.0

I also just tried it with these version and it continues to throw the same error:

Python 3.11.2
PyMongo 4.3.3

Okay, that explains it. Those URI options were renamed in PyMongo 4: PyMongo 4 Migration Guide — PyMongo 4.3.3 documentation

It’s working!

Thanks, @Steve_Silvester !

For those reading I added this to the end of my uri ?tls=true&tlsAllowInvalidCertificates=true

Great, thanks for following up!

Using tlsAllowInvalidCertificates=true or ssl_cert_reqs=CERT_NONE makes your TLS connection insecure. Instead your should install certifi (pip install --upgrade certifi) and pass tlsCAFile=certifi.where():

from urllib.parse import quote_plus

app.config["MONGO_URI"] = (
    f"mongodb+srv://<hidingusernameforpost>:<hidingpwdforpost>@cluster0.hpw8h6y.mongodb.net/dbName?tlsCAFile={quote_plus(certifi.where())}")
1 Like