Skip to main content
 首页 » 编程设计

python之mongoengine 使用身份验证数据库

2025年05月04日14yxwkf

我不确定如何连接到使用带有 mongoengine 的身份验证数据库的 mongodb 数据库。

在命令提示符下,我需要执行 mongo hostname:27017/myApp -u "test"-p "test"--authenticationDatabase admin,但我看不到要传递的位置这是作为 mongoengine 的参数,所以我使用 admin 数据库进行身份验证,但连接到我的模型的 myApp 数据库?

我相信这是 PyMongo 指南中解释的地方:

https://api.mongodb.com/python/current/examples/authentication.html

>>> from pymongo import MongoClient 
>>> client = MongoClient('example.com') 
>>> db = client.the_database 
>>> db.authenticate('user', 'password', source='source_database') 

我找到了将其添加到 mongoengine 的拉取请求:

https://github.com/MongoEngine/mongoengine/pull/590/files

看起来您只是将 authentication_source 添加为 connect 的参数,例如 connect(authentication_source='admin')。如果能更好地记录就更好了。

http://docs.mongoengine.org/apireference.html?highlight=authentication_source

请您参考如下方法:

根据mongoengine connecting guide , connect() 方法支持 URI 风格的连接。即

connect( 
   'project1' 
   host='mongodb://username:password@host1:port1/databaseName' 
) 

从这个意义上说,您还可以指定身份验证源数据库,如下所示:

"mongodb://username:password@host1:port1/database?authSource=source_database" 

另见 MongoDB connection string URI有关更多 MongoDB URI 示例。 还有 Authentication options through connection string