1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| from pymongo import MongoClient
from baseConfig import DATABASE
DB_CONF = DATABASE['mongodb']
def singleton(cls): """单例模式""" _instance = {} def _slt(*args, **kwargs): if cls not in _instance: _instance[cls] = cls(*args, **kwargs) return _instance[cls] return _slt
@singleton class MongoHandler(object): """创建MongoDB处理类""" def __init__(self, **kwargs): print(kwargs) self.db_name = kwargs['name'] or 'test_db' client = MongoClient() self.db = client[self.db_name] def drop(self): try: self.db.command("dropDatabase") except Exception as e: print("Delete DATABASE {0} failed! due to the reason of '{1}'".format(self.db_name, e)) def collection(self, cl): return self.db[cl] def insert_one_record(self, col, record: dict): """ 可以直接用得到的结合调用库方法, 这里限定类型,做演示用, 以下方法类似,根据业务需要改写 """ result = col.insert_one(record) print(result) def insert_many_records(self, col, records: list): result = col.insert_many(records) print(result) def find_one_record(self, col, condition: dict): result = col.find_one(condition) return result def find_records(self, col, condition: dict): results = col.find(condition) return results def update_one_record(self, col, condition: dict, data: dict): result = col.update_one(condition, data) print('影响修改条数:', result.matched_count, result.modified_count) return result def update_records(self, col, condition: dict, data: dict): result = col.update_many(condition, data) print('影响修改条数:', result.matched_count, result.modified_count) return result def delete_one_record(self, col, condition: dict): result = col.delete_one({'name': 'Kevin'}) return result.deleted_count def delete_records(self, col, condition: dict): result = col.delete_many(condition) return result.deleted_count
|