from pymongo import MongoClient
from bson.objectid import ObjectId
class AnimalShelter(object):
#CRUD operations for animals collection in MongoDB
def __init__(self, username, password):
#initializing Mongo Client
self.client = MongoClient('mongodb://%s:%s@127.0.0.1:53310/AAC' % (username, password))
self.database = self.client['AAC']
# Method to implement the C in CRUD
def create(self, data):
if data is not None:
if data:
self.database.animals.insert_one(data)
return True
else:
return False
def read(self, search):
if search is not None:
if search:
searchResult = self.database.animals.find(search)
return searchResult
else:
exception = ("Nothing to see here folks.")
return exception
This is my class that I created, I am trying to test the output.
from animal_shelter import AnimalShelter
#defining data
data = {"age_upon_outcome" : "3 years",
"animal_id" : "A746874",
"animal_type" : "Cat",
"breed" : "Domestic Shorthair Mix",
"color" : "Black/White",
"date_of_birth" : "2014-04-10",
"datetime" : "2017-04-11 09:00:00",
"monthyear" : "2017-04-11T09:00:00",
"name" : "",
"outcome_subtype" : "SCRP",
"outcome_type" : "Transfer",
"sex_upon_outcome" : "Neutered Male",
"location_lat" : 30.5066578739455,
"location_long" : -97.3408780722188,
"age_upon_outcome_in_weeks" : 156.767857142857}
#search criteria
search = {"animal_id":"A746874"}
#instantiating an object
assignment = AnimalShelter()
#calling the method
success = assignment.create(data)
print(success)
#call read method
results = assignment.read(search)
print(results)
I keep getting this error which I am having trouble understanding and correcting. I thought I was adding or importing the database when I initialized the mongo client. So how is it that my object doesn't have a database?
TypeError Traceback (most recent call last)
<ipython-input-22-5434d1614df4> in <module>
26
27 #calling the method
---> 28 success = assignment.create(data)
29 print(success)
30
AttributeError: 'AnimalShelter' object has no attribute 'database'
I am unsure about how to actually correct this. Is there a connection that I am not making between my class that I am creating and the mongo database that I am wanting to use?