python mongodb操作

1827 ワード

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を受け入れます.