Mongoengine-命令查找需要身份验证

时间:2019-02-27 02:31:11

标签: python mongodb pymongo mongoengine

我不熟悉将Mongoengine与经过身份验证的MongoDB一起使用。

我有一个名为“ gambit_test”的Mongo数据库。我已经启用了身份验证,并且我有一个正确的用户可以向数据库进行身份验证以执行读写操作。

我在Mongo Client中使用以下命令为“ gambit_test”创建了用户:

use gambit_test
db.createUser({
    user: "gambit_admin",
    pwd: "xxxxxx",
    roles:[{role: "userAdmin" , db:"admin"}]
})

当我登录MongoDB来检查用户状态时,我使用如下命令(以超级管理员身份登录):

mongo -u sup_admin -p yyyyyyyy

要验证我的用户状态,请执行以下操作:

use gambit_test
show users

它返回以下内容:

{
    "_id" : "gambit_test.gambit_admin",
    "user" : "gambit_admin",
    "db" : "gambit_test",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "gambit_test"
        },
        {
            "role" : "dbAdmin",
            "db" : "gambit_test"
        }
    ],
    "mechanisms" : [
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
    ]
}

在我的Python test.py代码中,这是我正在做的事情:

from mongoengine import *

class History(Document):
    name = StringField(required=True)

if __name__ == "__main__":
    try:
        connect('gambit_test')
        History.objects().get()
    except Exception as e: 
        connect(host='mongodb://gambit_admin:xxxxxx@localhost' + 
        ':27017/gambit_test')
        History.objects().get()

当我尝试运行上述python代码时,出现以下错误:

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    History.objects().get()
  File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/mongoengine/queryset/base.py", line 267, in get
    result = six.next(queryset)
  File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/mongoengine/queryset/base.py", line 1484, in __next__
    raw_doc = six.next(self._cursor)
  File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/pymongo/cursor.py", line 1189, in next
    if len(self.__data) or self._refresh():
  File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/pymongo/cursor.py", line 1104, in _refresh
    self.__send_message(q)
  File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/pymongo/cursor.py", line 982, in __send_message
    helpers._check_command_response(first)
  File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/pymongo/helpers.py", line 155, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
  pymongo.errors.OperationFailure: command find requires authentication

我不知道为什么会这样。原因是我可以使用Mongo客户端执行常规的find()和insert()。但是,当我使用Mongoengine时,事情就崩溃了……

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

为进一步参考,问题已解决(https://github.com/MongoEngine/mongoengine/issues/2010) 问题是第二个connect调用没有覆盖第一个调用设置的default连接,只是被默默忽略了