improve AnimalShelter class

This commit is contained in:
2024-03-11 21:10:18 -04:00
parent 31830844a4
commit 4c525f55c1
3 changed files with 106 additions and 69 deletions

View File

@@ -1,27 +1,41 @@
from pymongo import MongoClient
from bson.objectid import ObjectId
class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """
"""
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')
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
#
@@ -29,64 +43,49 @@ class AnimalShelter(object):
self.database = self.client['%s' % (DB)]
self.collection = self.database['%s' % (COL)]
# Complete this create method to implement the C in CRUD.
# 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:
raise Exception(f'Error: {e}')
print(f'Exception: {e}')
return False
else:
raise Exception("Nothing to save, because data parameter is empty")
# Create method to implement the R in CRUD.
print("Nothing to save, because data parameter is empty")
return False
# Read
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}")
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):
criteria = kwargs.get('criteria', None)
update_one = kwargs.get('once', False)
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
if update_one:
try:
self.collection.update_one(criteria, {f'${update_type}': data})
except Exception as e:
raise Exception(f"Error: {e}")
else:
try:
self.collection.update_many(criteria, {f'${update_type}': data})
except Exception as e:
raise Exception(f'Error: {e}')
# Delete
def delete(self, *args, **kwargs):
criteria = kwargs.get('criteria', None)
delete_one = kwargs.get('once', False)
if delete_one:
try:
self.collection.delete_one(criteria)
except Exception as e:
raise Exception(f'Error: {e}')
else:
try:
self.collection.delete_many(criteria)
except Exception as e:
raise Exception(f'Error: {e}')
query = kwargs.get('query', None)
try:
self.collection.delete_many(query)
return True
except Exception as e:
print(f'Exception: {e}')
return False

View File

@@ -1,5 +1,8 @@
from AnimalShelter import AnimalShelter
test = AnimalShelter()
test = AnimalShelter(
password='Ex9Ai3Y2eP',
host='db'
)
test_criteria = {"breed": "Protogen"}
test_data = test.read(criteria=test_criteria)

35
project1.ipynb Normal file
View File

@@ -0,0 +1,35 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "initial_id",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}