简体   繁体   English

为什么 PyMongo 3 给出 ServerSelectionTimeoutError?

[英]Why is PyMongo 3 giving ServerSelectionTimeoutError?

I'm using:我正在使用:

  • Python 3.4.2 Python 3.4.2
  • PyMongo 3.0.2 PyMongo 3.0.2
  • mongolab running mongod 2.6.9 mongolab 运行 mongod 2.6.9
  • uWSGI 2.0.10 uWSGI 2.0.10
  • CherryPy 3.7.0 CherryPy 3.7.0
  • nginx 1.6.2 nginx 1.6.2

uWSGI start params: uWSGI 启动参数:

--socket 127.0.0.1:8081 --daemonize --enable-threads --threads 2 --processes 2

I setup my MongoClient ONE time:我设置了我的 MongoClient 一次:

self.mongo_client = MongoClient('mongodb://user:pw@host.mongolab.com:port/mydb')
self.db = self.mongo_client['mydb']

I try and save a JSON dict to MongoDB:我尝试将 JSON 字典保存到 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:它通过执行与 mongodb 相同代码路径的单元测试来工作。但是,当我使用 HTTP POST 通过 CherryPy 和 uWSGI 执行时,我得到这个:

pymongo.errors.ServerSelectionTimeoutError: No servers found yet

Why am I seeing this behavior when run via CherryPy and uWSGI?为什么我在通过 CherryPy 和 uWSGI 运行时会看到这种行为? Is this perhaps the new thread model in PyMongo 3?这可能是 PyMongo 3 中的新线程 model 吗?

Update:更新:

If I run without uWSGI and nginx by using the CherryPy built-in server, the insert_one() works.如果我通过使用 CherryPy 内置服务器在没有 uWSGI 和 nginx 的情况下运行,则insert_one()可以工作。

Update 1/25 4:53pm EST:美国东部时间 1 月 25 日下午 4:53 更新:

After adding some debug in PyMongo, it appears that topology._update_servers() knows that the server_type = 2 for server 'myserver-a.mongolab.com'.在 PyMongo 中添加一些调试后, topology._update_servers()似乎知道服务器“myserver-a.mongolab.com”的 server_type = 2。 However server_description.known_servers() has the server_type = 0 for server 'myserver.mongolab.com'但是server_description.known_servers()的 server_type = 0 服务器 '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

We're investigating this problem, tracked in PYTHON-961 .我们正在调查这个问题,在PYTHON-961 中进行了跟踪。 You may be able to work around the issue by passing connect=False when creating instances of MongoClient.您可以通过在创建 MongoClient 实例时传递connect=False来解决此问题。 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.这将后台连接推迟到尝试第一次数据库操作之前,避免了我怀疑 MongoClient 的监视器线程的启动和多进程分叉之间的竞争条件。

As mentioned here: https://stackoverflow.com/a/54314615/8953378正如这里提到的: https : //stackoverflow.com/a/54314615/8953378

I added ?ssl=true&ssl_cert_reqs=CERT_NONE to my connection string, and it fixed the issue.我在我的连接字符串中添加了?ssl=true&ssl_cert_reqs=CERT_NONE ,它解决了这个问题。

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 & ) (请注意,如果您的连接字符串中有其他参数,则需要将?更改为&

I fixed it for myself by downgrading from pymongo 3.0 to 2.8.我通过从 pymongo 3.0 降级到 2.8 为自己修复了它。 No idea what's going on.不知道发生了什么。

   flask/bin/pip uninstall pymongo
   flask/bin/pip install pymongo==2.8

我在 Pymongo 3.5 上遇到了同样的问题结果将 localhost 替换为 127.0.0.1 或您的 mongodb 实例的相应 IP 地址解决了问题。

I am not sure if you are using the MongoDB paired with AWS Cloud service.我不确定您是否正在使用与 AWS 云服务配对的 MongoDB。 But if you are, I found that you have to specify which IP Address you want MongoDB to have access to.但是,如果您是,我发现您必须指定您希望 MongoDB 访问哪个 IP 地址。

So what you need to do is add the IP Address of your host server to allow entry.因此,您需要做的是添加主机服务器的 IP 地址以允许进入。

In MongoAtlas, this can be done at this page在 MongoAtlas 中,这可以在此页面完成在此处输入图片说明

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.我知道已经有针对同一问题的解决方案,但我没有找到对我的情况有帮助的解决方案,因此想发布此信息,以便其他人在遇到与我相同的问题时受益。

I solved this by installing dnspython (pip install dnspython).我通过安装 dnspython (pip install dnspython) 解决了这个问题。 The issue is that: "The "dnspython" module must be installed to use mongodb+srv:// URIs"问题是:“必须安装“dnspython”模块才能使用 mongodb+srv:// URIs”

In my case就我而言

  • I was using Mongo Atlas我正在使用 Mongo Atlas
  • I got another IP adress after a router reboot路由器重启后我得到了另一个 IP 地址

hence I had to add that IP to the whitelist on Mongo Atlas settings via因此我必须通过以下方式将该 IP 添加到Mongo Atlas 设置的白名单中

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然后等待 IP 地址的状态更改为活动,然后再次尝试运行该应用程序

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 .就我而言,代理设置可能阻止了连接,因为我可以通过更改 wifi成功建立到 mongodb 的连接。 Even if this question is marked as solved already, it can hopefully narrow down the problem for some others.即使这个问题被标记为已经解决,它也有望缩小其他一些问题的范围。

I encountered this too.我也遇到了这个。

This could be due to pymongo3 isn't fork safe .这可能是由于pymongo3 is not fork safe

I fix this by adding --lazy-apps param to uwsgi, this can avoid the "fork safe" problem.我通过向--lazy-apps添加--lazy-apps参数来解决这个问题,这可以避免“分叉安全”问题。

seeing uwsgi doc preforking-vs-lazy-apps-vs-lazy .看到uwsgi文档preforking-vs-lazy-apps-vs-lazy

Notice, no sure for this two having positive connection.请注意,不确定这两者是否具有正相关关系。

我遇到了同样的问题,最后我发现客户端 IP 被 mongo 服务器的防火墙阻止了。

maybe you can try to add your server ip address into the mongod.conf file.也许您可以尝试将您的服务器 IP 地址添加到 mongod.conf 文件中。 if you use linux(ubuntu) os,you can try my solution:如果您使用 linux(ubuntu) 操作系统,您可以尝试我的解决方案:

  1. modify mongod.conf file:修改 mongod.conf 文件:

     vi /etc/mongod.conf

    and you can add mongodb server ip address behind 127.0.0.1,and save:您可以在 127.0.0.1 后面添加 mongodb 服务器 ip 地址,并保存:

     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.现在,您可以尝试使用 pymongo MongoClient 连接 mongodb。

That error has occurred because there is no MongoDB server running in the background.发生该错误是因为后台没有运行 MongoDB 服务器。 To run the MongoDB server open cmd or anaconda prompt and type this:-要运行 MongoDB 服务器,请打开 cmd 或 anaconda 提示符并键入:-

"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe"

then run然后运行

import pymongo
myclient = pymongo.MongoClient()    
mydb = myclient["mydatabase"]
myclient.list_database_names()

I'm using pymongo 3.2 and I run into the same error, however it was a missconfiguration in my case.我正在使用 pymongo 3.2 并且遇到了同样的错误,但是在我的情况下这是一个错误配置。 After enabling authorization, I forgot to update the port in the url which ended up in a connection timout.启用授权后,我忘记更新最终导致连接超时的 url 中的端口。 Probably it is worth to mention that ?authSource might be required as it is typically different than the database storing the application data.可能值得一提的是 ?authSource 可能是必需的,因为它通常不同于存储应用程序数据的数据库。

I commented out bindIP variable in mongod.conf instead of allowing all connections (for which you have to enter 0.0.0.0).我在 mongod.conf 中注释掉了 bindIP 变量,而不是允许所有连接(您必须输入 0.0.0.0)。 Of course, beware of the consequence.当然,要注意后果。

pymongo 3 will not tell you your connection failed when you instantiate your client.当您实例化客户端时,pymongo 3 不会告诉您连接失败。 You may not be connected.您可能未连接。

https://api.mongodb.com/python/3.5.1/api/pymongo/mongo_client.html 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:" “如果它们不可用,它不再引发 ConnectionFailure .. 您可以像这样检查服务器是否可用:”

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")

The developers are investigating this problem, tracked in PYTHON-961 .开发人员正在调查这个问题,在PYTHON-961 中进行了跟踪。 You may be able to work around the issue by running mongod.exe manually and monitoring it.您可以通过手动运行 mongod.exe 并对其进行监控来解决此问题。 This issue arises when the console freezes and you can hit the enter if the mongod console is got stuck.当控制台冻结时会出现此问题,如果 mongod 控制台卡住,您可以按回车键。 This is the simplest solution for now until the developers fix this bug.在开发人员修复此错误之前,这是目前最简单的解决方案。

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).这是因为 mongodb 没有在我的本地机器上运行( sudo systemctl restart mongod让 mongodb 在 Ubuntu 上运行)。

I simply added my current IP address in the network access tab, as it got changed automatically.我只是在network access选项卡中添加了我当前的 IP 地址,因为它会自动更改。 Deleted the earlier one, there was a slight change in IP address.删除了之前的一个,IP地址略有变化。

I faced the same error on windows and I just started the MongoDB service我在 Windows 上遇到了同样的错误,我刚刚启动了 MongoDB 服务

  • open services ctrl+R then type services.msc then Enter打开服务 ctrl+R 然后输入 services.msc 然后回车

就我而言,我只设置我的 ip 允许列表 0.0.0.0 允许任何地方,但您可以使用“我的 ip 是什么”设置您的 ip 并将其复制粘贴到网络访问 > 添加 ip

Go to your Atlas Console > Network Access, then add your client IP address, Ex.转到您的 Atlas 控制台 > 网络访问,然后添加您的客户端 IP 地址,例如。 0.0.0.0/00 (Note: All client ips can access your database) 0.0.0.0/00(注意:所有客户端ip都可以访问你的数据库)

网络访问页面

I have been struggling with same problem.我一直在努力解决同样的问题。 Read and either insert did not work at all failed with ServerSelectionTimeoutError . Read 和 insert 根本不起作用,因为ServerSelectionTimeoutError失败。

I have been using pymongo==3.11.4 on Ubuntu 18.04 LTS.我一直在 Ubuntu 18.04 LTS 上使用pymongo==3.11.4 Tried use connect=False , pass extra ?ssl=true&ssl_cert_reqs=CERT_NONE options to my connection string and other suggestions listed above.尝试使用connect=False ,将额外的?ssl=true&ssl_cert_reqs=CERT_NONE选项传递给我的连接字符串和上面列出的其他建议。 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.最后 simple 尝试升级到pymongo==3.12.1并且连接开始工作而不传递connect=false ,并建议其他extra arguments

    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)

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.我设法通过以下方式处理它:安装 dnspython 库 > 转到 MongoDB 网页 > 登录 > 安全 > 网络访问 > 添加 IP 地址 > 添加来自我的请求的 IP 地址。

Hope this could help someone.希望这可以帮助某人。

Make sure you entered the user password, not the MongoDB account password.确保您输入的是用户密码,而不是 MongoDB 帐户密码。 I encountered similar issue.我遇到了类似的问题。 In my case, I mistakenly entered the MongoDB account password instead of the user password.就我而言,我错误地输入了 MongoDB 帐户密码而不是用户密码。

I had the same issue..the code that was working perfectly fine 2 minutes before gave this error.我有同样的问题.. 2 分钟前运行良好的代码给出了这个错误。 I was looking for solutions over google for about 30 minutes and it automatically got fixed.我在谷歌上寻找解决方案大约 30 分钟,它自动得到修复。 The problem could be my home inte.net 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.只是一个猜测,但如果您没有对代码或任何其他配置文件进行任何更改,最好等待一段时间再重试。

I was also facing the same issue.我也面临同样的问题。 Then, I added然后,我补充说

import certifi
Client = MongoClient("mongodb+srv://<username>:<password>@cluster0.ax9ugoz.mongodb.net/?retryWrites=true&w=majority", tlsCAFile=certifi.where())

and it solved my issue.它解决了我的问题。

Certifi provides a collection of Root Certificates for validating the trustworthiness of SSL certificates while verifying the identity of TLS hosts. Certifi 提供了一组根证书,用于验证 SSL 证书的可信度,同时验证 TLS 主机的身份。

这已通过pull_request 在PyMongo得到修复。

This problem solved when I just toggled the MongoDB in the services to running which was stopped previously.当我刚刚将服务中的MongoDB切换到之前停止的运行时,这个问题就解决了。 mongodb 服务部分

  • First set up the MongoDB environment.首先设置MongoDB环境。

  • Run this on CMD - "C:\\Program Files\\MongoDB\\Server\\3.6\\bin\\mongod.exe"在 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"打开另一个 CMD 并运行这个 - “C:\\Program Files\\MongoDB\\Server\\3.6\\bin\\mongo.exe”

And then you can use pymongo [anaconda prompt]然后你可以使用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/参考 - https://docs.mongodb.com/tutorials/install-mongodb-on-windows/

If it can help, I solved by replace :如果有帮助,我通过替换解决了:

from flask.ext.mongoengine import MongoEngine

by :经过 :

from flask_mongoengine import MongoEngine

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ServerSelectionTimeoutError Pymongo - ServerSelectionTimeoutError Pymongo pymongo.errors.ServerSelectionTimeoutError - pymongo.errors.ServerSelectionTimeoutError 升级到PyMongo 3.0导致ServerSelectionTimeoutError - Upgrade to PyMongo 3.0 Resulting in ServerSelectionTimeoutError 烧瓶 - pymongo.errors.ServerSelectionTimeoutError - Flask - pymongo.errors.ServerSelectionTimeoutError 使用 pymongo 连接到 aws 时出现 ServerSelectionTimeoutError - ServerSelectionTimeoutError when connecting to aws with pymongo pymongo.errors.ServerSelectionTimeoutError: RepliceSetNoPrimary - MongoDB Atlas - pymongo.errors.ServerSelectionTimeoutError: RepliceSetNoPrimary - MongoDB Atlas Pymongo读取首选项-ServerSelectionTimeoutError:无主要可用于写入 - Pymongo Read Preferences - ServerSelectionTimeoutError: No primary available for writes 使用 pymongo 连接到 Atlas MongoDb - ServerSelectionTimeoutError - Connecting to Atlas MongoDb using pymongo - ServerSelectionTimeoutError Pymongo pymongo.errors.ServerSelectionTimeoutError 使用示例代码时 - Pymongo pymongo.errors.ServerSelectionTimeoutError when using example code 尝试连接到 CosmosDB 数据库时出现 pymongo.errors.ServerSelectionTimeoutError - Getting pymongo.errors.ServerSelectionTimeoutError when attempting to connect to a CosmosDB database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM