databases.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from typing import Optional
  2. import redis
  3. from pymongo import MongoClient
  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, coll: str, cfg: Optional[dict] = mongo_conf):
  11. self.client = MongoClient(host=cfg['host'], port=cfg['port'])
  12. self.db: Database = self.client[db]
  13. self.collection: Collection = self.db[coll]
  14. def __enter__(self):
  15. return self.collection
  16. def __exit__(self, exc_type, exc_val, exc_tb):
  17. self.client.close()
  18. class RedisDBS:
  19. """ redis """
  20. def __init__(self, cfg: Optional[dict] = redis_conf):
  21. pool = redis.ConnectionPool(
  22. host=cfg['host'],
  23. port=cfg['port'],
  24. password=cfg['pwd'],
  25. db=cfg['db']
  26. )
  27. self.__r = redis.Redis(connection_pool=pool, decode_responses=True)
  28. @property
  29. def redis(self):
  30. return self.__r