封装pymongo工具类时,报错:pymongo.errors.OperationFailure: Authentication failed.
class MongoUtil:
def __init__(self, host, port, username, password, db_name):
self.host = host
self.port = port
self.username = username
self.password = password
self.client = pymongo.MongoClient('mongodb://{}:{}@{}:{}'.format(self.username,self.password,self.host,self.port))
self.db = self.client[db_name]
原因:
如果将用户名密码写入pymongo.MongoClient中,默认连接的数据库是admin,事实上我所连接的数据库并不是admin,所以,用户名和密码是无效的,所以导致认证失败。
解决办法:
在pymongo.MongoClient中中指定所要连接的数据库,
或者是在选择数据库之后 self.db = self.client[db_name]
之后
添加认证 db.authenticate('username', 'password')
def __init__(self, host, port, username, password, db_name):
self.host = host
self.port = port
self.username = username
self.password = password
self.client = pymongo.MongoClient('mongodb://{}:{}'.format(self.host,self.port))
self.db = self.client[db_name]
self.authenticate= self.db.authenticate(self.username,self.password)