Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding get and count method to the DBStorage and FileStorage #3723

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added __pycache__/console.cpython-313.pyc
Binary file not shown.
39 changes: 24 additions & 15 deletions console.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/python3
""" console """
"""console"""

import cmd
from datetime import datetime
Expand All @@ -13,20 +13,28 @@
from models.user import User
import shlex # for splitting the line along spaces except in double quotes

classes = {"Amenity": Amenity, "BaseModel": BaseModel, "City": City,
"Place": Place, "Review": Review, "State": State, "User": User}
classes = {
"Amenity": Amenity,
"BaseModel": BaseModel,
"City": City,
"Place": Place,
"Review": Review,
"State": State,
"User": User,
}


class HBNBCommand(cmd.Cmd):
""" HBNH console """
prompt = '(hbnb) '
"""HBNH console"""

prompt = "(hbnb) "

def do_EOF(self, arg):
"""Exits console"""
return True

def emptyline(self):
""" overwriting the emptyline method """
"""overwriting the emptyline method"""
return False

def do_quit(self, arg):
Expand All @@ -38,18 +46,18 @@ def _key_value_parser(self, args):
new_dict = {}
for arg in args:
if "=" in arg:
kvp = arg.split('=', 1)
kvp = arg.split("=", 1)
key = kvp[0]
value = kvp[1]
if value[0] == value[-1] == '"':
value = shlex.split(value)[0].replace('_', ' ')
value = shlex.split(value)[0].replace("_", " ")
else:
try:
value = int(value)
except:
except Exception:
try:
value = float(value)
except:
except Exception:
continue
new_dict[key] = value
return new_dict
Expand Down Expand Up @@ -125,8 +133,8 @@ def do_all(self, arg):
def do_update(self, arg):
"""Update an instance based on the class name, id, attribute & value"""
args = shlex.split(arg)
integers = ["number_rooms", "number_bathrooms", "max_guest",
"price_by_night"]
integers = ["number_rooms", "number_bathrooms",
"max_guest", "price_by_night"]
floats = ["latitude", "longitude"]
if len(args) == 0:
print("** class name missing **")
Expand All @@ -140,12 +148,12 @@ def do_update(self, arg):
if args[2] in integers:
try:
args[3] = int(args[3])
except:
except Exception:
args[3] = 0
elif args[2] in floats:
try:
args[3] = float(args[3])
except:
except Exception:
args[3] = 0.0
setattr(models.storage.all()[k], args[2], args[3])
models.storage.all()[k].save()
Expand All @@ -160,5 +168,6 @@ def do_update(self, arg):
else:
print("** class doesn't exist **")

if __name__ == '__main__':

if __name__ == "__main__":
HBNBCommand().cmdloop()
1 change: 1 addition & 0 deletions file.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"Amenity.b7adbf93-0f98-413d-99c0-d1e0377015e5": {"id": "b7adbf93-0f98-413d-99c0-d1e0377015e5", "created_at": "2025-02-14T17:03:28.627653", "updated_at": "2025-02-14T17:03:28.627653", "__class__": "Amenity"}, "BaseModel.65ad860c-d3db-4b5b-9424-0ef9a3c97bee": {"id": "65ad860c-d3db-4b5b-9424-0ef9a3c97bee", "created_at": "2025-02-14T17:03:28.627673", "updated_at": "2025-02-14T17:03:28.627673", "__class__": "BaseModel"}, "City.800dd67a-c506-484e-9149-79a5a5bf06c4": {"id": "800dd67a-c506-484e-9149-79a5a5bf06c4", "created_at": "2025-02-14T17:03:28.627684", "updated_at": "2025-02-14T17:03:28.627684", "__class__": "City"}, "Place.3aab944f-b6f9-42ec-ac4f-239ac8bb7816": {"id": "3aab944f-b6f9-42ec-ac4f-239ac8bb7816", "created_at": "2025-02-14T17:03:28.627693", "updated_at": "2025-02-14T17:03:28.627693", "__class__": "Place"}, "Review.f2c9189f-cf24-41b5-a022-39e4d3d100ce": {"id": "f2c9189f-cf24-41b5-a022-39e4d3d100ce", "created_at": "2025-02-14T17:03:28.627702", "updated_at": "2025-02-14T17:03:28.627702", "__class__": "Review"}, "State.d5c8cad5-fa7c-4595-bcdf-05e8dc76d773": {"id": "d5c8cad5-fa7c-4595-bcdf-05e8dc76d773", "created_at": "2025-02-14T17:03:28.627711", "updated_at": "2025-02-14T17:03:28.627711", "__class__": "State"}, "User.1cfd7d8d-d838-49a4-b892-63e4e1e20fa2": {"id": "1cfd7d8d-d838-49a4-b892-63e4e1e20fa2", "created_at": "2025-02-14T17:03:28.627719", "updated_at": "2025-02-14T17:03:28.627719", "__class__": "User"}}
Binary file added models/__pycache__/__init__.cpython-313.pyc
Binary file not shown.
Binary file added models/__pycache__/amenity.cpython-313.pyc
Binary file not shown.
Binary file added models/__pycache__/base_model.cpython-313.pyc
Binary file not shown.
Binary file added models/__pycache__/city.cpython-313.pyc
Binary file not shown.
Binary file added models/__pycache__/place.cpython-313.pyc
Binary file not shown.
Binary file added models/__pycache__/review.cpython-313.pyc
Binary file not shown.
Binary file added models/__pycache__/state.cpython-313.pyc
Binary file not shown.
Binary file added models/__pycache__/user.cpython-313.pyc
Binary file not shown.
Binary file added models/engine/__pycache__/__init__.cpython-313.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
69 changes: 55 additions & 14 deletions models/engine/db_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,34 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

classes = {"Amenity": Amenity, "City": City,
"Place": Place, "Review": Review, "State": State, "User": User}
classes = {
"Amenity": Amenity,
"City": City,
"Place": Place,
"Review": Review,
"State": State,
"User": User,
}


class DBStorage:
"""interaacts with the MySQL database"""

__engine = None
__session = None

def __init__(self):
"""Instantiate a DBStorage object"""
HBNB_MYSQL_USER = getenv('HBNB_MYSQL_USER')
HBNB_MYSQL_PWD = getenv('HBNB_MYSQL_PWD')
HBNB_MYSQL_HOST = getenv('HBNB_MYSQL_HOST')
HBNB_MYSQL_DB = getenv('HBNB_MYSQL_DB')
HBNB_ENV = getenv('HBNB_ENV')
self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.
format(HBNB_MYSQL_USER,
HBNB_MYSQL_PWD,
HBNB_MYSQL_HOST,
HBNB_MYSQL_DB))
HBNB_MYSQL_USER = getenv("HBNB_MYSQL_USER")
HBNB_MYSQL_PWD = getenv("HBNB_MYSQL_PWD")
HBNB_MYSQL_HOST = getenv("HBNB_MYSQL_HOST")
HBNB_MYSQL_DB = getenv("HBNB_MYSQL_DB")
HBNB_ENV = getenv("HBNB_ENV")
self.__engine = create_engine(
"mysql+mysqldb://{}:{}@{}/{}".format(
HBNB_MYSQL_USER, HBNB_MYSQL_PWD, HBNB_MYSQL_HOST, HBNB_MYSQL_DB
)
)
if HBNB_ENV == "test":
Base.metadata.drop_all(self.__engine)

Expand All @@ -47,9 +54,9 @@ def all(self, cls=None):
if cls is None or cls is classes[clss] or cls is clss:
objs = self.__session.query(classes[clss]).all()
for obj in objs:
key = obj.__class__.__name__ + '.' + obj.id
key = obj.__class__.__name__ + "." + obj.id
new_dict[key] = obj
return (new_dict)
return new_dict

def new(self, obj):
"""add the object to the current database session"""
Expand All @@ -74,3 +81,37 @@ def reload(self):
def close(self):
"""call remove() method on the private session attribute"""
self.__session.remove()

def get(self, cls, id):
"""
Method to retrieve one object: Returns the object based on the class
and its ID or NONE if not found
"""
if cls and id:
if cls in classes.values() and isinstance(id, str):
all_objects = self.all(cls)

for key, value in all_objects.items():
if key.split(".")[1] == id:
return value
else:
return
return

def count(self, cls=None):
"""
Method to count the number of objects in storage:
Returns the no of objects in storage matching the given class.
If no class id passed,
Returns the count of all objects in storage
"""
if not cls:
inst_of_all_cls = self.all()
return len(inst_of_all_cls)

if cls in classes.values():
all_inst_of_prov_cls = self.all(cls)
return len(all_inst_of_prov_cls)

if cls not in classes.values():
return
52 changes: 46 additions & 6 deletions models/engine/file_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,15 @@
from models.state import State
from models.user import User

classes = {"Amenity": Amenity, "BaseModel": BaseModel, "City": City,
"Place": Place, "Review": Review, "State": State, "User": User}
classes = {
"Amenity": Amenity,
"BaseModel": BaseModel,
"City": City,
"Place": Place,
"Review": Review,
"State": State,
"User": User,
}


class FileStorage:
Expand Down Expand Up @@ -45,26 +52,59 @@ def save(self):
json_objects = {}
for key in self.__objects:
json_objects[key] = self.__objects[key].to_dict()
with open(self.__file_path, 'w') as f:
with open(self.__file_path, "w") as f:
json.dump(json_objects, f)

def reload(self):
"""deserializes the JSON file to __objects"""
try:
with open(self.__file_path, 'r') as f:
with open(self.__file_path, "r") as f:
jo = json.load(f)
for key in jo:
self.__objects[key] = classes[jo[key]["__class__"]](**jo[key])
except:
except Exception:
pass

def delete(self, obj=None):
"""delete obj from __objects if it’s inside"""
if obj is not None:
key = obj.__class__.__name__ + '.' + obj.id
key = obj.__class__.__name__ + "." + obj.id
if key in self.__objects:
del self.__objects[key]

def close(self):
"""call reload() method for deserializing the JSON file to objects"""
self.reload()

def get(self, cls, id):
"""
Method to retrieve one object: Returns the object based on the class
and its ID or NONE if not found
"""
if cls and id:
if cls in classes.values():
all_objects = self.all(cls)

for value in all_objects.values():
if value.id == id:
return value
return
return

def count(self, cls=None):
"""
Method to count the number of objects in storage:
Returns the no of objects in storage matching the given class.
If no class id passed,
Returns the count of all objects in storage
"""
if not cls:
inst_of_all_cls = self.all()
return len(inst_of_all_cls)

if cls in classes.values():
all_inst_of_prov_cls = self.all(cls)
return len(all_inst_of_prov_cls)

if cls not in classes.values():
return None
Binary file added tests/__pycache__/__init__.cpython-313.pyc
Binary file not shown.
Binary file added tests/__pycache__/test_console.cpython-313.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading