120 lines
4.4 KiB
Python
120 lines
4.4 KiB
Python
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, **kwargs):
|
|
"""
|
|
Creates collection objects using a defined dictionary
|
|
|
|
:param data:
|
|
Dictionary with the data that will be created in the database
|
|
"""
|
|
data = kwargs.get('data', None)
|
|
if data is not None:
|
|
try:
|
|
self.database.animals.insert_one(data)
|
|
return True
|
|
except Exception as e:
|
|
print(f'Exception: {e}') # Exception handling
|
|
return False # Failed operation, so return false
|
|
else:
|
|
print("Nothing to save, because data parameter is empty") # Case of empty 'data' parameter
|
|
return False # Failed operation, so return false
|
|
# Read
|
|
def read(self, **kwargs):
|
|
"""
|
|
Accepts a query and returns a list of dictionaries with the requested data from the collection
|
|
|
|
:param query:
|
|
The filter that will be used to query the database
|
|
"""
|
|
query = kwargs.get('query', None)
|
|
dataList = []
|
|
try:
|
|
dataList = [doc for doc in self.collection.find(query)] # MongoDB cursor, we need to convert this to a list of dicts
|
|
return dataList # Return the list
|
|
except Exception as e:
|
|
print(f'Exception: {e}') # Exception handling
|
|
return [] # Return empty list
|
|
# Update
|
|
def update(self, **kwargs):
|
|
"""
|
|
Updates objects in the collection based on the query, update type, and incoming dict of data
|
|
|
|
:param query:
|
|
The filter that will be used to query the database for the objects that will be updated
|
|
:param update_type:
|
|
The type of update to be performed, accepts any MongoDB Field Update Operator
|
|
(https://www.mongodb.com/docs/manual/reference/operator/update-field/)
|
|
:param data:
|
|
The incoming data (dictionary) to update with
|
|
Not required depending on the update_type specified
|
|
"""
|
|
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}) # Query DB + update with data
|
|
return True # Operation was successful, so return true
|
|
except Exception as e:
|
|
print(f'Exception: {e}') # Exception handling
|
|
return False # Failed operation, so return false
|
|
|
|
# Delete
|
|
def delete(self, **kwargs):
|
|
"""
|
|
Deletes objects in the collection based on the query
|
|
|
|
:param query:
|
|
The filter that will be used to query the database for objects that will be deleted
|
|
"""
|
|
query = kwargs.get('query', None)
|
|
try:
|
|
self.collection.delete_many(query)
|
|
return True # Operation was successful, so return true
|
|
except Exception as e:
|
|
print(f'Exception: {e}') # Exception handling
|
|
return False # Failed operation, so return false
|