utils_mongo_handle.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # -*-coding: utf-8 -*-
  2. import pymongo
  3. from pymongo import errors
  4. import time
  5. import sys
  6. import os
  7. sys.path.append(os.path.join(os.path.abspath(__file__).split('auto')[0] + 'auto'))
  8. from base.base_load_config import load_config, get_base_path
  9. config_json = load_config()
  10. base_project = get_base_path()
  11. DB_USER = config_json.get('DB_USER')
  12. DB_PASSWORD = config_json.get('DB_PASSWORD')
  13. DB_IP = config_json.get('DB_IP')
  14. DB_PORT = config_json.get('DB_PORT')
  15. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  16. class MongoHandle(object):
  17. def __init__(self, db, collection, del_db=False, del_collection=False, auto_remove=0):
  18. self.client = pymongo.MongoClient(MONGO_LINK)
  19. self.db = db
  20. self.collection = collection
  21. if del_db and db:
  22. # 检查数据库是否存在
  23. if db in self.client.list_database_names():
  24. # 删除数据库
  25. self.client.drop_database(db)
  26. self.db = self.client[db]
  27. if del_collection and self.collection:
  28. # 检查集合是否存在
  29. if self.collection in self.db.list_collection_names():
  30. # 删除集合
  31. self.db.drop_collection(collection)
  32. self.collection = self.db[collection]
  33. if auto_remove:
  34. self.auto_remove_data(auto_remove)
  35. def write_data(self, data):
  36. self.collection.insert_one(data)
  37. def load_data(self):
  38. # MongoDB 会在第一次写入时自动创建数据库和集合
  39. return list(self.collection.find({}, {'_id': False}))
  40. def auto_remove_data(self, day):
  41. for data in self.collection.find({'create_time': {'$lt': int(time.time()) - day * 24 * 60 * 60}}):
  42. self.collection.delete_one({'_id': data['_id']})
  43. # if __name__ == '__main__':
  44. # mongo = MongoHandle('test_db', 'test_collection', False, False, 0)
  45. # mongo.collection.insert_one({'name': 'test'})
  46. # mongo.collection.insert_many([{'name': 'test1'}, {'name': 'test2'}])
  47. # print(mongo.collection.find_one())
  48. # print(mongo.collection.find())
  49. # print('done!')