from pymongo import MongoClient from bson.objectid import ObjectId class AnimalShelter(object): """ CRUD operations for Animal collection in MongoDB """ def __init__(self): # Initializing the MongoClient. This helps to # access the MongoDB databases and collections. # This is hard-wired to use the aac database, the # animals collection, and the aac user. # Definitions of the connection string variables are # unique to the individual Apporto environment. # # You must edit the connection variables below to reflect # your own instance of MongoDB! # # Connection Variables # USER = 'aacuser' PASS = 'Ex9Ai3Y2eP' HOST = 'db' PORT = 27017 DB = 'AAC' COL = 'animals' # # Initialize Connection # self.client = MongoClient('mongodb://%s:%s@%s:%d' % (USER,PASS,HOST,PORT)) self.database = self.client['%s' % (DB)] self.collection = self.database['%s' % (COL)] # Complete this create method to implement the C in CRUD. def create(self, *args, **kwargs): data = kwargs.get('data', None) if data is not None: try: self.database.animals.insert_one(data) # data should be dictionary except Exception as e: raise Exception(f'Error: {e}') else: raise Exception("Nothing to save, because data parameter is empty") # Create method to implement the R in CRUD. def read(self, *args, **kwargs): criteria = kwargs.get('criteria', None) find_one = kwargs.get('once', False) if find_one: try: data = self.collection.find_one(criteria) return data except Exception as e: raise Exception(f"Error: {e}") else: try: data = self.collection.find(criteria) return data except Exception as e: raise Exception(f"Error: {e}")