tools_mongo_handle.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*-coding: utf-8 -*-
  2. import pymongo
  3. import time
  4. import tools_load_config
  5. config_json = tools_load_config.load_config()
  6. base_project = tools_load_config.get_base_path()
  7. DB_USER = config_json.get('DB_USER')
  8. DB_PASSWORD = config_json.get('DB_PASSWORD')
  9. DB_IP = config_json.get('DB_IP')
  10. DB_PORT = config_json.get('DB_PORT')
  11. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  12. class MongoHandle(object):
  13. def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
  14. self.client = pymongo.MongoClient(MONGO_LINK)
  15. self.db = db
  16. self.collection = collection
  17. if del_db and db:
  18. # 检查数据库是否存在
  19. if db in self.client.list_database_names():
  20. # 删除数据库
  21. self.client.drop_database(db)
  22. self.db = self.client[db]
  23. if del_collection and self.collection:
  24. # 检查集合是否存在
  25. if self.collection in self.db.list_collection_names():
  26. # 删除集合
  27. self.db.drop_collection(collection)
  28. self.collection = self.db[collection]
  29. if auto_remove:
  30. self.auto_remove_data(auto_remove)
  31. def write_data(self, data):
  32. self.collection.insert_one(data)
  33. def auto_remove_data(self, day):
  34. for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
  35. self.collection.delete_one({'_id': data['_id']})
  36. # if __name__ == '__main__':
  37. # mongo = MongoHandle('test_db', 'test_collection', False, False, 0)
  38. # mongo.collection.insert_one({'name': 'test'})
  39. # mongo.collection.insert_many([{'name': 'test1'}, {'name': 'test2'}])
  40. # print(mongo.collection.find_one())
  41. # print(mongo.collection.find())
  42. # print('done!')