python-mongo部分方法封裝

近來,實現存儲樣式的需求時用到了mongo數據庫,順便封裝了一波(熟練下基本操作)。

代碼如下:

# coding=utf-8
from pymongo import MongoClient, database, collection, ASCENDING

mongo_url_local = "mongodb://用戶名:密碼@server IP/"


class mongodb:
    def __init__(self, url=None, database='iot_db'):
        self.__mongourl = url if url is not None else mongo_url_local
        # 通過mongoclient連接mongo server而非connection連接--mongoclient默認進行安全檢測
        self.__mongoclient = None
        self.__mongodb = database
        self.db_handle = self.__connect()

    def __connect(self):
        """
        :return: 成功返回數據庫句柄,失敗返回None
        """
        self.__mongoclient = MongoClient(self.__mongourl)
        # 連接數據庫
        try:
            db_handle = database.Database(self.__mongoclient, self.__mongodb)
            return db_handle
        except Exception as e:
            print('mongodb connect error:', e)
            return None

    def __del__(self):
        # 關閉數據庫服務器連接
        if self.__mongoclient is not None:
            self.__mongoclient.close()
            print('__del__ callback')
        else:
            pass

    def insert(self, table, records):
        """
        :param table: 數據庫表名
        :param records: 待插入的記錄(一條/多條)
        :return: bool type
        """
        ret = False
        try:
            if isinstance(records, list):
                self.db_handle[table].insert_many(records)
                ret = True
            elif isinstance(records, dict):
                self.db_handle[table].insert_one(records)
                ret = True
            else:
                print('parameter type error!')
                return False
            return ret
        except Exception as e:
            print('insert error:', e)
            return False

    def delete(self, table, condition, flag=None):
        """
        :param table: 數據庫表名
        :param condition: 待刪除記錄的條件
        :flag: flag== 'all' 清空表所有記錄
        :return: bool type
        """
        ret = False
        try:
            if isinstance(condition, list):
                size = len(condition)
                for i in range(0, size):
                    self.db_handle[table].delete_many(condition[i])
                    # self.db_handle[table].remove({query}) 等價於樓上
                ret = True
            elif isinstance(condition, dict):
                self.db_handle[table].delete_many(condition)
                ret = True
            else:
                print('parameter type error!')
                ret = False
            if flag == 'all':
                self.db_handle[table].remove()
            else:
                pass
            return ret
        except Exception as e:
            print('delete error:', e)
            return False

    def update(self, table, condition, result):
        """
        :param table:
        :param condition: 待修改記錄的條件 字典類型
        :param result: 字段名:更新後結果 字典類型
        :return: bool type
        """
        try:
            result = self.db_handle[table].update_many(condition, {"$set": result})
            return result
        except Exception as e:
            print('delete error:', e)
            return None

    def find(self, table, action=None, condition=None, para=None, sort_type=1):
        """
        :param table: 數據庫表
        :param condition: 篩選條件
        :param action: limit sort count distinct None依次爲:
        結果集數量限制  對滿足過濾條件的記錄排序 滿足過濾條件的記錄個數  滿足過濾條件的不重複記錄個數 查詢該表下所有記錄
        :param para: action爲limit時 para爲數字 action爲sort para爲排序依據的字段
        :param sort_type: action爲sort para爲排序依據的字段 sort_type == -1時降序排序 sort_type == 1 時升序排序
        :return: 記錄(列表)/某個字段列表/滿足篩選條件的記錄數量
        """
        ret = []
        result = None
        try:
            if action == 'limit':
                result = self.db_handle[table].find(condition).limit(para)
            elif action == 'sort':
                # 升序排序
                if sort_type == 1:
                    result = self.db_handle[table].find(condition).sort(para)
                # 降序排序
                elif sort_type == -1:
                    result = self.db_handle[table].find(condition).sort(para, -1)
                # 參數錯誤
                else:
                    ret = None
                    print('sort_type error!')
            elif action == 'count':
                result = self.db_handle[table].find(condition).count(True)
                return result
            elif action == 'distinct':
                result = self.db_handle[table].find(condition).distinct(para)
                return result
            elif action == 'None':
                if condition is None:
                    result = self.db_handle[table].find()
                else:
                    result = self.db_handle[table].find(condition)
            else:
                ret = None
                print('parameter type error!')
            if result is not None:
                for i in result:
                    ret.append(i)
            return ret
        except Exception as e:
            print('find error:', e)
            return None

    def find_count(self, table, condition):
        """
        滿足過濾條件的記錄個數
        :param table:  表
        :param condition:  過濾條件
        :return:
        """
        try:
            result = self.db_handle[table].count_documents(condition)
            return result
        except Exception as e:
            print('find_count error:', e)
            return None

    def table_count(self, table):
        """
        求表記錄個數
        :param table: 表
        :return:
        """
        try:
            result = self.db_handle[table].count(True)
            return result
        except Exception as e:
            print('table_count error:', e)
            return None

    def creates_index(self, table, key):
        """
        爲表創建索引
        :param table:
        :param key: 索引名字
        :return:
        """
        try:
            self.db_handle[table].create_index(key)
            return True
        except Exception as e:
            print('creates_index error:', e)
            return False

    def lists_index_information(self, table):
        """
        查看錶索引信息
        :param table:
        :return:
        """
        try:
            result = self.db_handle[table].index_information()
            return result
        except Exception as e:
            print('lists_index_information error:', e)
            return None

    def lists_index(self, table):
        """
        查看錶索引
        :param table:
        :return:
        """
        ret = []
        try:
            result = self.db_handle[table].list_indexes()
            for i in result:
                ret.append(i)
            return ret
        except Exception as e:
            print('lists_index error:', e)
            return None

    def drops_index(self, table, key):
        """
        刪除表索引
        :param key:
        :param table:
        :return:
        """
        result = False
        try:
            if key is None:
                result = False
            else:
                self.db_handle[table].drop_index(key)
                result = True
        except Exception as e:
            print('drops_index error:', e)
            result = False
        finally:
            return result


if __name__ == '__main__':
    mongo_db = mongodb()
    # -----------插入測試---------
    datas = {'name': 'upt2', 'id': 'reach', 'age': 12306.7}
    print('insert', mongo_db.insert('test_lijietao', datas))
    print('insert', mongo_db.insert('test_lijietao', [{'name': 'upt3', 'id': 'reach', 'age': 12306.8},
                                                      {'name': 'upt4', 'id': 'reach', 'age': 12306.9},
                                                      {'name': 'upt5', 'id': 'reach', 'age': 12307.0},
                                                      {'name': 'upt6', 'id': 'reach', 'age': 12308.0},
                                                      {'name': 'upt6', 'id': 'reach', 'age': 12308.1},
                                                      {'name': 'upt6', 'id': 'reach', 'age': 12308.2},
                                                      {'name': 'upt6', 'id': 'reach', 'age': 12308.3}]))
    # ----------刪除測試----------
    print('delete', mongo_db.delete('test_lijietao', {'name': 'upt1'}))
    print('delete', mongo_db.delete('test_lijietao', [{'name': 'upt2'}, {'name': 'upt3'}]))

    # ----------修改測試----------
    print('update', mongo_db.update('test_lijietao', {'name': 'upt4'}, {'age': 12304.0, 'name': 'change4'}))

    # ----------查詢測試----------
    mongo_db.insert('test_lijietao', [{'name': 'upt7', 'id': 'reach', 'age': 12308.1},
                                      {'name': 'upt7', 'id': 'reach', 'age': 12308.2},
                                      {'name': 'upt7', 'id': 'reach', 'age': 12308.3},
                                      {'name': 'upt7', 'id': 'reach', 'age': 12308.4},
                                      {'name': 'upt7', 'id': 'reach', 'age': 12308.5},
                                      {'name': 'upt7', 'id': 'reach', 'age': 12308.6},
                                      {'name': 'upt7', 'id': 'reach', 'age': 12308.7}])
    print('find', mongo_db.find('test_lijietao', 'limit', {'name': 'upt7'}, 2))
    print('find', mongo_db.find('test_lijietao', 'sort', {'name': 'upt7'}, 'age', 1))
    print('find', mongo_db.find('test_lijietao', 'sort', {'name': 'upt7'}, 'age', -1))
    print('find', mongo_db.find('test_lijietao', 'count', {'name': 'upt7'}))
    print('find', mongo_db.find('test_lijietao', 'distinct', {'name': 'upt7'}, 'age'))
    print('find', mongo_db.find('test_lijietao', 'None'))
    print('find', mongo_db.find('test_lijietao', 'None', {"age": {"$lt": 12306.0}}))
    print('find', mongo_db.find_count('test_lijietao', {'name': 'upt7'}))
    print('table_count', mongo_db.table_count('test_lijietao'))

    # ------------創建索引----------
    print('creates_index', mongo_db.creates_index('test_lijietao', [("age", ASCENDING)]))

    # ------------顯示索引----------
    print('lists_index', mongo_db.lists_index('test_lijietao'))
    print('lists_index_information', mongo_db.lists_index_information('test_lijietao'))

    # ------------刪除索引----------
    print('drops_index', mongo_db.drops_index('test_lijietao', 'age_1'))
    print('lists_index', mongo_db.lists_index('test_lijietao'))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章