class MongoClient(object):
def __init__(self, db_name, collections_name):
super(MongoClient, self).__init__()
host = settings[MongoConstant.MONGO_SERVER]
port = settings[MongoConstant.MONGO_PORT]
self.__check_settings(host, port, db_name, collections_name)
db = pymongo.MongoClient(host, port)[str(db_name)]
user = settings[MongoConstant.MONGO_USER]
password = settings[MongoConstant.MONGO_PASSWD]
if user is not None and password is not None:
db.authenticate(user, password)
self.collections = {}
if isinstance(collections_name, list) or isinstance(collections_name, tuple):
for collection in collections_name:
self.collections[collection] = db[collection]
else:
self.collections[collections_name] = db[collections_name]
def __check_settings(self, host, port, db, collection):
if self.__check_var(host) and self.__check_var(port) and \
self.__check_var(db) and self.__check_var(collection):
return
else:
raise ValueError
@classmethod
def __check_var(cls, var):
return False if var is None or '' else True
def insert(self, collection, item):
self.collections[collection].insert(item, check_keys=False)
如果设置了用户和密码,db.authenticate(user, password)
登录即可,由于python的参数传递可不指定类型,故我们可以接受多种参数类型的collections_name
,如果为list
或者元祖tuple
,我们可以定义一个字典self.collections = {}
将collections
以键值对的形式保存起来,使用的时候只需要根据collection name将对应的链接取出来操作即可self.collections[collection].insert(item, check_keys=False)
,当然一般我们接受一个clooection_name
。
网友评论