无法使用flask-mongoengine连接到远程MongoDB服务器

时间:2016-09-28 21:37:10

标签: python mongodb pymongo mongoengine flask-mongoengine

尝试使用flask-mongoengine连接到远程服务器上托管的MongoDB群集,但会引发以下错误:

File "test.py", line 9, in <module>
    inserted = Something(some='whatever').save()
  File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/mongoengine/document.py", line 323, in save
    object_id = collection.save(doc, **write_concern)
  File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/collection.py", line 2186, in save
    with self._socket_for_writes() as sock_info:
  File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__
    return next(self.gen)
  File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/mongo_client.py", line 762, in _get_socket
    server = self._get_topology().select_server(selector)
  File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/topology.py", line 210, in select_server
    address))
  File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/topology.py", line 186, in select_servers
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: admin:27017: [Errno -2] Name or service not known

以下是我正在使用的代码:

# test.py

from my_app_module import app
from flask_mongoengine import MongoEngine

db = MongoEngine(app)

class Something(db.Document):
    some = db.StringField()

inserted = Something(some='whatever').save()

print(inserted)
for obj in Something.objects:
    print(obj)

我的config.py文件包含:

# config.py

MONGODB_SETTINGS = {
    'db': 'testdb',
    'host': 'mongodb://<my_username>:<my_password>@<my_cluster_replica_1>.mongodb.net:27017,<my_cluster_replica_2>.mongodb.net:27017,<my_cluster_replica_3>.mongodb.net:27017/admin?ssl=true&replicaSet=<my_cluster>&authSource=admin',
}

但我可以使用以下代码使用pymongo进行连接。

from pymongo import MongoClient

uri = 'mongodb://<my_username>:<my_password>@<my_cluster_replica_1>.mongodb.net:27017,<my_cluster_replica_2>.mongodb.net:27017,<my_cluster_replica_3>.mongodb.net:27017/admin?ssl=true&replicaSet=<my_cluster>&authSource=admin'

client = MongoClient(uri)
db = client['testdb']

db.test_collection.insert({'some_key': 'some_value'})

for col in db.test_collection.find():
    print(col)

# Prints {'some_key': 'some_value', '_id': ObjectId('57ec35d9312f911329e54d5e')}

我试图找到一个解决方案,但似乎没有人遇到过这个问题。我正在使用MongoDB的Atlas解决方案来托管MongoDB集群。

1 个答案:

答案 0 :(得分:0)

我发现这是flask-mongoengine版本0.8中的一个错误,并且报告了here