from pymongo import MongoClient from bson.objectid import ObjectId class AnimalShelter(object): """ CRUD operations for Animal collection in MongoDB """ def __init__(self, **kwargs): """ Constructor for the AnimalShelter class, initializes the MongoDB connection :param user: The MongoDB database user to connect with (default: 'aacuser') :param password: The password for the aforementioned MongoDB user (no default... use your own!) :param host: The MongoDB server hostname/IP to connect to (default: 'localhost') :param port: The TCP port that the MongoDB server is listening on (default: 27017) :param db: The Animal Shelter MongoDB database (default: 'AAC') :param collection: MongoDB Collection for the animal records (default: 'animals') """ USER = kwargs.get('user', 'aacuser') PASS = kwargs.get('password', None) HOST = kwargs.get('host', 'localhost') PORT = kwargs.get('port', 27017) DB = kwargs.get('db', 'AAC') COL = kwargs.get('collection', '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)] # Create 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 return True except Exception as e: print(f'Exception: {e}') return False else: print("Nothing to save, because data parameter is empty") return False # Read def read(self, *args, **kwargs): query = kwargs.get('query', None) dataList = [] try: data = self.collection.find(query) for object in data: dataList.append(object) return dataList except Exception as e: print(f'Exception: {e}') return False # Update def update(self, *args, **kwargs): query = kwargs.get('query', None) update_type = kwargs.get('update_type', None) data = kwargs.get('data', None) try: self.collection.update_many(query, {f'${update_type}': data}) return True except Exception as e: print(f'Exception: {e}') return False # Delete def delete(self, *args, **kwargs): query = kwargs.get('query', None) try: self.collection.delete_many(query) return True except Exception as e: print(f'Exception: {e}') return False