databases.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import bson
  2. import pymongo
  3. import redis
  4. from config.load import mongo_conf, redis_conf
  5. # ---------------------------------- mongo ----------------------------------
  6. MONGO_URI_CLIENTS = {} # a dictionary hold all client with uri as key
  7. def mongo_client(cfg=None, host=None, port=None, fork=False, **kwargs):
  8. if host is not None and port is not None:
  9. uri = f'mongodb://{host}:{port}'
  10. else:
  11. _cfg = (cfg or mongo_conf)
  12. uri = f'mongodb://{_cfg["host"]}:{_cfg["port"]}'
  13. if fork:
  14. return pymongo.MongoClient(uri, **kwargs)
  15. global MONGO_URI_CLIENTS
  16. matched_client = MONGO_URI_CLIENTS.get(uri)
  17. if matched_client is None:
  18. new_client = pymongo.MongoClient(uri, **kwargs)
  19. if new_client is not None:
  20. MONGO_URI_CLIENTS[uri] = new_client
  21. return new_client
  22. return matched_client
  23. def mongo_database(name: str, **kw):
  24. client = mongo_client(**kw)
  25. return client.get_database(name)
  26. def mongo_table(db: str, name: str, **kw):
  27. database = mongo_database(db, **kw)
  28. return database.get_collection(name)
  29. def int2long(param: int):
  30. """int 转换成 long """
  31. return bson.int64.Int64(param)
  32. def object_id(_id: str):
  33. return bson.objectid.ObjectId(_id)
  34. # ---------------------------------- redis ----------------------------------
  35. def redis_client(cfg=None):
  36. if cfg is None:
  37. cfg = redis_conf
  38. pool = redis.ConnectionPool(
  39. host=cfg['host'],
  40. port=cfg['port'],
  41. password=cfg['pwd'],
  42. db=cfg['db']
  43. )
  44. return redis.Redis(connection_pool=pool, decode_responses=True)