Advertisement
Guest User

CRUD

a guest
Nov 19th, 2023
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.60 KB | None | 0 0
  1. from pymongo import MongoClient
  2. from bson.objectid import ObjectId
  3. import logging
  4.  
  5. ###########################
  6. #Configuring Logging Feature
  7. ###########################
  8.  
  9. logging.basicConfig(
  10. filename='AnimalShelter_CRUD.log', # Specify the log file name
  11. level=logging.INFO, # Set the logging level to INFO (you can change it)
  12. format='%(asctime)s - %(levelname)s - %(message)s' # Define log message format
  13. )
  14.  
  15.  
  16. class AnimalShelter(object):
  17. """ CRUD operations for Animal collection in MongoDB """
  18.  
  19. def __init__(self, aacuser, admin):
  20. # Initializing the MongoClient. This helps to
  21. # access the MongoDB databases and collections.
  22. self.client = MongoClient('mongodb://%s:%s@localhost:46703/AAC' % (aacuser, admin))
  23. self.database = self.client['AAC']
  24.  
  25. # Complete this create method to implement the C in CRUD.
  26. def create(self, data):
  27. if data is not None:
  28. try:
  29. insert = self.database.animals.insert(data) # data should be dictionary
  30. if insert != 0:
  31. logging.info("Record created successfully")
  32. return True
  33. else:
  34. logging.error("Failed to create record")
  35. return False
  36. except Exception as e:
  37. logging.error(f"Error while creating record: {str(e)}")
  38. return False
  39. else:
  40. logging.error("Nothing to save, data parameter is empty")
  41. raise Exception("Nothing to save, data parameter is empty")
  42.  
  43. # Create method to implement the R in CRUD.
  44. def read(self, criteria=None):
  45.  
  46. try:
  47. # If criteria is not None then this find will return all rows which match the criteria
  48. if criteria:
  49. # {'_id': False} omits the unique ID of each row
  50. data = self.database.animals.find(criteria, {"_id": False})
  51. else:
  52. # If there is no search criteria then all the rows will be returned
  53. data = self.database.animals.find({}, {"_id": False})
  54. assert isinstance(data, object)
  55. logging.info("Records read successfully")
  56. return data
  57. except Exception as e:
  58. logging.error(f"Error while reading records: {str(e)}")
  59. return None
  60.  
  61. # Create method to implement the U in CRUD
  62. def update(self, data, newvals):
  63. try:
  64. if data is not None:
  65. update_result = self.database.animals.update(data, newvals)
  66. if update_result.get("updatedExisting", False):
  67. logging.info("Record updated successfully")
  68. return True
  69. else:
  70. logging.error("Failed to update record")
  71. return False
  72. else:
  73. logging.error("Update unsuccessful. Data parameter is empty.")
  74. return False
  75. except Exception as e:
  76. logging.error(f"Error while updating record: {str(e)}")
  77. return False
  78.  
  79. # Create method to implement the D in CRUD
  80. def delete(self, data):
  81. try:
  82. if data is not None:
  83. self.database.animals.remove(data)
  84. logging.info("Record deleted successfully")
  85. return True
  86. else:
  87. logging.error("Delete unsuccessful. Data parameter is empty.")
  88. return False
  89. except Exception as e:
  90. logging.error(f"Error while deleting record: {str(e)}")
  91. return False
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement