databases.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import bson
  2. import pymongo
  3. import setting as settings
  4. # ---------------------------------- mongo ----------------------------------
  5. MONGO_URI_CLIENTS = {} # a dictionary hold all client with uri as key
  6. def mongo_client(cfg=None, host=None, port=None, fork=False, **kwargs):
  7. if host is not None and port is not None:
  8. uri = f'mongodb://{host}:{port}'
  9. else:
  10. _cfg = (cfg or settings.mongo_conf)
  11. uri = f'mongodb://{_cfg["host"]}:{_cfg["port"]}'
  12. if fork:
  13. return pymongo.MongoClient(uri, **kwargs)
  14. global MONGO_URI_CLIENTS
  15. matched_client = MONGO_URI_CLIENTS.get(uri)
  16. if matched_client is None:
  17. new_client = pymongo.MongoClient(uri, **kwargs)
  18. if new_client is not None:
  19. MONGO_URI_CLIENTS[uri] = new_client
  20. return new_client
  21. return matched_client
  22. def mongo_database(name: str, **kw):
  23. client = mongo_client(**kw)
  24. return client.get_database(name)
  25. def mongo_table(db: str, name: str, **kw):
  26. database = mongo_database(db, **kw)
  27. return database.get_collection(name)
  28. def int2long(param: int):
  29. """int 转换成 long """
  30. return bson.int64.Int64(param)
  31. def object_id(_id: str):
  32. return bson.objectid.ObjectId(_id)