class MogoContext():
def __init__(self,rw='r',db='cmdb2') -> None:
user='cmdb_user'
pwd='1q2w3e'
host='host'
# self.uri="mongodb://%s:%s@%s" % (quote_plus(user), quote_plus(pwd), host)
# db 指定要连接的数据库,
# user/pwd指定数据库的用户密码
self.client = MongoClient(host=host, port=27017, username=user, password=pwd,authSource=db)
# conn = MongoClient('mongodb://{}:{}@{}:{}/?authSource={}'.format(user,pwd,host,27017,db))
self.db=self.client[db]
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.client.close()
if __name__=='__main__':
with MogoContext('r','cmdb2') as mongo:
stu=mongo.db['student'].find_one({"Name":"ab"})
print(str(stu))