连接本机或局域网部署的mongodb时可以用以下方法:
1 from urllib import parse 2 from pymongo import MongoClient 3 4 host = ‘*.*.*.*‘ 5 username = ‘*****‘ 6 password = ‘****‘ 7 passwd = parse.quote(password) # 对密码先进行编码 8 port = ‘3717‘ 9 mongo_url = ‘mongodb://{0}:{1}@{2}:{3}‘.format(username, passwd, host, port) 10 clinet = MongoClient(mongo_url)
但连接集群部署的mongodb时,再用以上代码连接,会报错:pymongo.errors.OperationFailure: not authorized
因为mongoDB有不同的认证机制,3.0版本以后采用的是‘SCRAM-SHA-1‘, 之前的版本采用的是‘MONGODB-CR‘,所以首先需要查看自己连接的mongodb的版本号
需要更改连接方式,代码如下:
from pymongo import MongoClient host = ‘**.**.**.**‘ username = ‘*****‘ password = ‘....‘ port = ‘3717‘ db = ‘test‘ mongo_url = ‘mongodb://{0}:{1}@{2}:{3}/?authSource={4}&authMechanism=SCRAM-SHA-1‘.format(username, password, host, port,db) clinet = MongoClient(mongo_url)
authMechanism参数根据自己的版本号,写对应的值就可以了
原文地址:https://www.cnblogs.com/benben-wu/p/10312689.html
时间: 2024-10-11 10:19:55