Guest User

Untitled

a guest
Dec 12th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.84 KB | None | 0 0
  1. class DataAccess(metaclass=Singleton):
  2. def __init__(self):
  3. self.client = None
  4. self.db_client = None
  5. self.connect()
  6.  
  7. @auto_retry_decorator
  8. def connect(self):
  9. """connect to db"""
  10. try:
  11. host = os.getenv(inventory_constants.DB_HOST)
  12. port = os.getenv(inventory_constants.DB_PORT)
  13. username = os.getenv(inventory_constants.DB_USER)
  14. password = os.getenv(inventory_constants.DB_PASSWORD)
  15.  
  16. logging.info("Connecting to mongodb")
  17. uri = "mongodb" + "://"+username+":"+password+"@"+host+":"+port
  18. self.client = pymongo.MongoClient(uri, connect=False,
  19. appname="")
  20.  
  21. self.db_client = self.client[os.getenv(inventory_constants.DB_NAME)]
  22. except ConnectionFailure as ex:
  23. logging.error(ex)
  24. raise DBConnectionFailure(ex)
  25.  
  26. @auto_retry_decorator
  27. def create(self, collection_name, records):
  28. try:
  29. logging.info("Creating the collection in db.")
  30. collection = self.db_client[collection_name]
  31. is_list = isinstance(records, list)
  32. if is_list: # array, use insert_many
  33. logging.info("Performing insert many operation.")
  34. result = collection.insert_many(records)
  35. return True, result.inserted_ids
  36. logging.info("Performing insert one operation")
  37. result = collection.insert_one(records)
  38. return True, result.inserted_id
  39. except BaseException as ex:
  40. logging.exception(ex)
  41. logging.error("Error while performing insert operations.")
  42. raise DataBaseError(ex)
  43.  
  44. @auto_retry_decorator
  45. def get(self, collection_name, filter_dictionary={}, **kwargs):
  46.  
  47. try:
  48. is_dictionary = isinstance(filter_dictionary, dict)
  49. if not is_dictionary:
  50. logging.warning("DB Get operation: filter_dict is not a instance of dict")
  51. raise TypeError(message_consts.INVALID_TYPE_DEFAULT)
  52. count = 0
  53. records = []
  54. limit, skip = get_limit_skip(**kwargs)
  55. if kwargs.get("sort_by") and kwargs.get("order_by"):
  56. cursor = get_document_order_by(self, collection_name, filter_dictionary,
  57. limit=limit, skip=skip, **kwargs)
  58. elif limit:
  59. cursor = get_document_limit(self, collection_name, filter_dictionary,
  60. limit=limit, skip=skip, **kwargs)
  61. else:
  62. cursor = get_document(self, collection_name, filter_dictionary, **kwargs)
  63.  
  64. for each_row in cursor:
  65. count = count + 1
  66. records.append(each_row)
  67. logging.info("DB GET operation: count %s of records. ", count)
  68.  
  69. return count, records
  70. except BaseException as ex:
  71. logging.error("Error while performing db get operation")
  72. logging.exception(ex)
  73. raise DataBaseError(ex)
  74.  
  75. Traceback (most recent call last):
Add Comment
Please, Sign In to add comment