Why is PyMongo 3 giving ServerSelectionTimeoutError?
PythonMongodbUwsgiMlabPymongo 3.xPython Problem Overview
I'm using:
- Python 3.4.2
- PyMongo 3.0.2
- mongolab running mongod 2.6.9
- uWSGI 2.0.10
- CherryPy 3.7.0
- nginx 1.6.2
uWSGI start params:
--socket 127.0.0.1:8081 --daemonize --enable-threads --threads 2 --processes 2
I setup my MongoClient ONE time:
self.mongo_client = MongoClient('mongodb://user:[email protected]:port/mydb')
self.db = self.mongo_client['mydb']
I try and save a JSON dict to MongoDB:
result = self.db.jobs.insert_one(job_dict)
It works via a unit test that executes the same code path to mongodb. However when I execute via CherryPy and uWSGI using an HTTP POST, I get this:
pymongo.errors.ServerSelectionTimeoutError: No servers found yet
Why am I seeing this behavior when run via CherryPy and uWSGI? Is this perhaps the new thread model in PyMongo 3?
Update:
If I run without uWSGI and nginx by using the CherryPy built-in server, the insert_one()
works.
Update 1/25 4:53pm EST:
After adding some debug in PyMongo, it appears that topology._update_servers()
knows that the server_type = 2 for server 'myserver-a.mongolab.com'. However server_description.known_servers()
has the server_type = 0 for server 'myserver.mongolab.com'
This leads to the following stack trace:
result = self.db.jobs.insert_one(job_dict)
File "/usr/local/lib/python3.4/site-packages/pymongo/collection.py", line 466, in insert_one
with self._socket_for_writes() as sock_info:
File "/usr/local/lib/python3.4/contextlib.py", line 59, in __enter__
return next(self.gen)
File "/usr/local/lib/python3.4/site-packages/pymongo/mongo_client.py", line 663, in _get_socket
server = self._get_topology().select_server(selector)
File "/usr/local/lib/python3.4/site-packages/pymongo/topology.py", line 121, in select_server
address))
File "/usr/local/lib/python3.4/site-packages/pymongo/topology.py", line 97, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: No servers found yet
Python Solutions
Solution 1 - Python
We're investigating this problem, tracked in PYTHON-961. You may be able to work around the issue by passing connect=False when creating instances of MongoClient. That defers background connection until the first database operation is attempted, avoiding what I suspect is a race condition between spin up of MongoClient's monitor thread and multiprocess forking.
Solution 2 - Python
As mentioned here: https://stackoverflow.com/a/54314615/8953378
I added ?ssl=true&ssl_cert_reqs=CERT_NONE
to my connection string, and it fixed the issue.
so instead of:
connection_string = "mongodb+srv://<USER>:<PASSWORD>@<CLUSTER>/<COLLECTION>"
I wrote:
connection_string = "mongodb+srv://<USER>:<PASSWORD>@<CLUSTER>/<COLLECTION>?ssl=true&ssl_cert_reqs=CERT_NONE"
(Note that if you have other parameters in your connection string, you need to change the ?
to &
)
Solution 3 - Python
I fixed it for myself by downgrading from pymongo 3.0 to 2.8. No idea what's going on.
flask/bin/pip uninstall pymongo
flask/bin/pip install pymongo==2.8
Solution 4 - Python
I am not sure if you are using the MongoDB paired with AWS Cloud service. But if you are, I found that you have to specify which IP Address you want MongoDB to have access to.
So what you need to do is add the IP Address of your host server to allow entry.
In MongoAtlas, this can be done at this page
I know there was already a solution to the same issue, but I didn't find a solution that helped my situation, so wanted to post this, so others could benefit if they ever face the same problem that I do.
Solution 5 - Python
I had the same problem with Pymongo 3.5 Turns out replacing localhost with 127.0.0.1 or corresponding ip address of your mongodb instance solves the problem.
Solution 6 - Python
I solved this by installing dnspython (pip install dnspython). The issue is that: "The "dnspython" module must be installed to use mongodb+srv:// URIs"
Solution 7 - Python
In my case
- I was using Mongo Atlas
- I got another IP adress after a router reboot
hence I had to add that IP to the whitelist on Mongo Atlas settings via
MongoAtlas website -> Network Access -> IP Whitelist -> Add IP Address -> Add Current IP Address
then wait for IP Address's status to change to Active and then try to run the app again
if you are using a repl.it server to host, just add the host ip you used to configure your server, for me it was 0.0.0.0, which is the most common
Solution 8 - Python
I was facing the same exception today. In my case, the proxy settings were probably blocking the connection since I could establish a successful connection to the mongodb by changing my wifi. Even if this question is marked as solved already, it can hopefully narrow down the problem for some others.
Solution 9 - Python
I've come accross the same problem and finally I found that the client IP is blocked by the firewall of the mongo server.
Solution 10 - Python
I encountered this too.
This could be due to pymongo3 isn't fork safe.
I fix this by adding --lazy-apps
param to uwsgi, this can avoid the "fork safe" problem.
seeing uwsgi doc preforking-vs-lazy-apps-vs-lazy.
Notice, no sure for this two having positive connection.
Solution 11 - Python
pymongo 3 will not tell you your connection failed when you instantiate your client. You may not be connected.
https://api.mongodb.com/python/3.5.1/api/pymongo/mongo_client.html
"it no longer raises ConnectionFailure if they are unavailable .. You can check if the server is available like this:"
from pymongo.errors import ConnectionFailure
client = MongoClient()
try:
# The ismaster command is cheap and does not
require auth.
client.admin.command('ismaster')
except ConnectionFailure:
print("Server not available")
Solution 12 - Python
Go to your Atlas Console > Network Access, then add your client IP address, Ex. 0.0.0.0/00 (Note: All client ips can access your database)
Solution 13 - Python
maybe you can try to add your server ip address into the mongod.conf file. if you use linux(ubuntu) os,you can try my solution:
-
modify mongod.conf file:
vi /etc/mongod.conf
and you can add mongodb server ip address behind 127.0.0.1,and save:
net:
port:27017
bindIp:127.0.0.1,mongodb server ip
2. in the teminal:
`sudo service mongod restart`
Now,you can try to connect mongodb by using pymongo MongoClient.
Solution 14 - Python
That error has occurred because there is no MongoDB server running in the background. To run the MongoDB server open cmd or anaconda prompt and type this:-
"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe"
then run
import pymongo
myclient = pymongo.MongoClient()
mydb = myclient["mydatabase"]
myclient.list_database_names()
Solution 15 - Python
I'm using pymongo 3.2 and I run into the same error, however it was a missconfiguration in my case. After enabling authorization, I forgot to update the port in the url which ended up in a connection timout. Probably it is worth to mention that ?authSource might be required as it is typically different than the database storing the application data.
Solution 16 - Python
I commented out bindIP variable in mongod.conf instead of allowing all connections (for which you have to enter 0.0.0.0). Of course, beware of the consequence.
Solution 17 - Python
The developers are investigating this problem, tracked in PYTHON-961. You may be able to work around the issue by running mongod.exe manually and monitoring it. This issue arises when the console freezes and you can hit the enter if the mongod console is got stuck. This is the simplest solution for now until the developers fix this bug.
Solution 18 - Python
I ran into the same issue during development. It was due to the fact that mongodb wasn't running on my local machine (sudo systemctl restart mongod
to get mongodb running on Ubuntu).
Solution 19 - Python
I simply added my current IP address in the network access
tab, as it got changed automatically. Deleted the earlier one, there was a slight change in IP address.
Solution 20 - Python
I faced the same error on windows and I just started the MongoDB service
- open services ctrl+R then type services.msc then Enter
Solution 21 - Python
For my case I only set my ip allow list 0.0.0.0 allow anywhere but you can set your ip using "what is my ip" and copy paste it to network access > add ip
Solution 22 - Python
I have been struggling with same problem. Read and either insert did not work at all failed with ServerSelectionTimeoutError
.
I have been using pymongo==3.11.4
on Ubuntu 18.04 LTS.
Tried use connect=False
, pass extra ?ssl=true&ssl_cert_reqs=CERT_NONE
options to my connection string and other suggestions listed above. In my case they didn't work.
Finally simple tried to upgrade to pymongo==3.12.1
and connection started to work without passing connect=false
, and other extra arguments
suggested.
login = '<USERNAME>'
password = '<PASSWORD>'
host = '*.mongodb.net'
db = '<DB>'
uri = f'mongodb+srv://{login}:{password}@{host}/{db}?retryWrites=true&w=majority'
client = MongoClient(uri, authsource='admin')#, connect=False)
collection = client.db.get_collection('collection_name')
# t = collection.find_one({'hello': '1'})
t = collection.insert_one({'hello': '2'})
print(t)
Solution 23 - Python
I had this issue today. I managed to deal with it by:
installing dnspython library > going to MongoDB webpage > signing in > security > network access > add IP address > adding the IP address from where my request comes from.
Hope this could help someone.
Solution 24 - Python
Make sure you entered the user password, not the MongoDB account password. I encountered similar issue. In my case, I mistakenly entered the MongoDB account password instead of the user password.
Solution 25 - Python
I had the same issue..the code that was working perfectly fine 2 minutes before gave this error. I was looking for solutions over google for about 30 minutes and it automatically got fixed. The problem could be my home internet connection. Just a guess but if you haven't made any changes to the code or any other config file best to wait for sometime and retry.
Solution 26 - Python
This has been fixed in PyMongo
with this pull_request.
Solution 27 - Python
This problem solved when I just toggled the MongoDB in the services to running which was stopped previously.
Solution 28 - Python
First set up the MongoDB environment.
- Run this on CMD - "C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe"
- Open another CMD and run this - "C:\Program Files\MongoDB\Server\3.6\bin\mongo.exe"
And then you can use pymongo [anaconda prompt]
import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.test_db
collection = db['test_coll']
Refer - https://docs.mongodb.com/tutorials/install-mongodb-on-windows/