databases.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from typing import Optional
  2. import pymongo
  3. import redis
  4. from pymongo.collection import Collection
  5. from pymongo.database import Database
  6. from config.load import mongo_conf, redis_conf
  7. __all__ = ['MongoDBS', 'RedisDBS']
  8. class MongoDBS:
  9. """ Mongo """
  10. def __init__(self, db: str, collection: str, cfg: dict = mongo_conf):
  11. self.client = pymongo.MongoClient(host=cfg['host'], port=cfg['port'])
  12. self.db: Database = self.client[db]
  13. self.coll: Collection = self.db[collection]
  14. def __enter__(self):
  15. return self.coll
  16. def __exit__(self, exc_type, exc_val, exc_tb):
  17. # 上下文管理器,实例调用完毕后,关闭客户端连接
  18. self.client.close()
  19. def __del__(self):
  20. # 实例调用完毕后,关闭客户端连接
  21. self.client.close()
  22. class RedisDBS:
  23. """ redis """
  24. def __init__(self, cfg: Optional[dict] = redis_conf):
  25. pool = redis.ConnectionPool(
  26. host=cfg['host'],
  27. port=cfg['port'],
  28. password=cfg['pwd'],
  29. db=cfg['db']
  30. )
  31. self.__r = redis.Redis(connection_pool=pool, decode_responses=True)
  32. @property
  33. def redis(self):
  34. return self.__r