我最近将 Bottle + uWSGI + Nginx 应用程序升级到 MongoDB 3.0.2。它在 PyMongo 2.8 上运行良好,但今天我通过运行以下命令升级到 PyMongo 3.0:
pip install --upgrade pymongo
我没有对代码进行任何其他更改,但现在我不断收到以下错误。
File "/pymongo/cursor.py", line 968, in __next__ if len(self.__data) or self._refresh():
File "/pymongo/cursor.py", line 905, in _refresh self.__read_preference))
File "/pymongo/cursor.py", line 812, in __send_message **kwargs)
File "/pymongo/mongo_client.py", line 716, in _send_message_with_response server = topology.select_server(selector)
File "/pymongo/topology.py", line 113, in select_server server_selection_timeout))
File "/pymongo/topology.py", line 93, in select_servers self._error_message(selector))
ServerSelectionTimeoutError: No servers found yet
我用来连接数据库的函数如下:
def connect_db(db_name):
global db
host = "localhost"
port = 27017
connection = pymongo.MongoClient(host=host, port=port)
db = connection[db_name]
我已经重新启动了所有服务器。静态页面工作正常,但任何尝试访问数据库的页面都会挂起并引发上述错误。但是,如果我去一个mongo
shell 或 Python shell 并查询 MongoDB 服务器,它工作正常。
>>> import pymongo
>>> host = "localhost"
>>> port = 27017
>>> connection = pymongo.MongoClient(host=host, port=port)
>>> db = connection[test]
>>> db.test.insert_one({"test": True});
<pymongo.results.InsertOneResult object at 0x7fc43b8efc80>
似乎只有我的应用程序找不到 MongoDB 服务器。请注意,我使用的是虚拟环境,以防以任何方式影响情况。另外,如果我降级回 PyMongo 2.8,一切都会正常。