我指的是 http://api.mongodb.org/python/current/examples/authentication.html 站点的身份验证机制示例。我创建了一个用户管理员并使用其凭据为我的“报告”数据库创建了一个用户。现在我需要使用用户名和密码通过 pymongo 访问它。我在 python shell 中尝试了以下命令。这是正确的方法吗,因为我的身份验证失败了。
from pymongo import MongoClient
client = MongoClient('localhost')
client.reporting.authenticate('reportsUser', '123456', mechanism='MONGODB-CR')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/pymongo/database.py", line 746, in authenticate
self.connection._cache_credentials(self.name, credentials)
File "/usr/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 441, in _cache_credentials
auth.authenticate(credentials, sock_info, self.__simple_command)
File "/usr/lib/python2.7/dist-packages/pymongo/auth.py", line 214, in authenticate
auth_func(credentials[1:], sock_info, cmd_func)
File "/usr/lib/python2.7/dist-packages/pymongo/auth.py", line 194, in _authenticate_mongo_cr
cmd_func(sock_info, source, query)
File "/usr/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 607, in __simple_command
helpers._check_command_response(response, None, msg)
File "/usr/lib/python2.7/dist-packages/pymongo/helpers.py", line 147, in _check_command_response
raise OperationFailure(msg % errmsg, code)
pymongo.errors.OperationFailure: command SON([('authenticate', 1), ('user', u'reportsUser'), ('nonce', u'f8158a24f1c61650'), ('key', u'14cea216c54b93bae20acd2e076bb785')]) failed: auth failed
最佳答案
仅供引用,您也可以使用 URI 字符串格式。伪代码如下所示:
pymongo.MongoClient('mongodb://user:password@server:port/')
这是一个带有身份验证的简单连接代码块:
import pymongo
conn = pymongo.MongoClient('mongodb://root:pass@localhost:27017/')
db = conn['database']
coll = db['collection']
此处查询字符串有更多选项:http://docs.mongodb.org/manual/reference/connection-string/
希望对您有所帮助 = 看起来您已经拥有它了。编码愉快!!
关于python - 我如何通过pymongo验证用户名密码以进行mongodb身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29508162/