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

Storage get count #3705

Open
wants to merge 5 commits 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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ No known bugs at this time.
## Authors
Alexa Orrico - [Github](https://github.com/alexaorrico) / [Twitter](https://twitter.com/alexa_orrico)
Jennifer Huang - [Github](https://github.com/jhuang10123) / [Twitter](https://twitter.com/earthtojhuang)
Peter Akinpelumi - [Github](https://github.com/Akinpete) / [Twitter](https://twitter.com/)

Second part of Airbnb: Joann Vuong
## License
Expand Down
Empty file added api/__init__.py
Empty file.
Empty file added api/v1/__init__.py
Empty file.
24 changes: 24 additions & 0 deletions api/v1/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/python3
"""
starts a Flask web application
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from flask import Flask, render_template
from models import storage
from api.v1.views import app_views

app = Flask(__name__)
app.register_blueprint(app_views)

@app.teardown_appcontext
def teardown_db(exception):
"""closes the storage on teardown"""
storage.close()

if __name__ == "__main__":
host = os.getenv('HBNB_API_HOST', '0.0.0.0')
port = int(os.getenv('HBNB_API_PORT', 5000))
app.run(host=host, port=port, threaded=True, debug=True)
10 changes: 10 additions & 0 deletions api/v1/views/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/python3
"""
set up app_views blueprint
"""

from flask import Blueprint

app_views = Blueprint('app_views', __name__, url_prefix='/api/v1')

from api.v1.views.index import *
11 changes: 11 additions & 0 deletions api/v1/views/index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/python3
"""
views for home/index page
"""
from flask import Flask, Blueprint, jsonify
from api.v1.views import app_views

@app_views.route('/status', strict_slashes=False)
def hbnbStatus():
"""hbnbStatus"""
return jsonify({"status": "OK"})
19 changes: 19 additions & 0 deletions launch_flask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import os
from api.v1.app import app

# Set environment variables
os.environ['HBNB_MYSQL_USER'] = 'hbnb_dev'
os.environ['HBNB_MYSQL_PWD'] = 'hbnb_dev_pwd'
os.environ['HBNB_MYSQL_HOST'] = 'localhost'
os.environ['HBNB_MYSQL_DB'] = 'hbnb_dev_db'
os.environ['HBNB_TYPE_STORAGE'] = 'db'
os.environ['HBNB_API_HOST'] = '0.0.0.0'
os.environ['HBNB_API_PORT'] = '5000'

# Retrieve the host and port from environment variables (with default values)
host = os.getenv('HBNB_API_HOST', '0.0.0.0')
port = int(os.getenv('HBNB_API_PORT', 5000))

# Launch the Flask app
if __name__ == "__main__":
app.run(host=host, port=port, threaded=True)
19 changes: 19 additions & 0 deletions models/engine/db_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,25 @@ def new(self, obj):
"""add the object to the current database session"""
self.__session.add(obj)

def get(self, cls, id):
"""Retrieve an object"""
if cls in classes.values():
result = self.__session.query(cls).filter(cls.id == id).first()
return result
else:
return None

def count(self, cls=None):
"""Count the number of objects in storage matching the given class.
If no class is passed, return the count of all objects in storage."""
total_count = 0
if cls is not None:
total_count = self.__session.query(cls).count()
else:
for clss in classes.values():
total_count += self.__session.query(clss).count()
return total_count

def save(self):
"""commit all changes of the current database session"""
self.__session.commit()
Expand Down
19 changes: 18 additions & 1 deletion models/engine/file_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@ def all(self, cls=None):
return new_dict
return self.__objects

def get(self, cls, id):
"""Retrieve an object"""
if cls in classes.values():
key = cls.__name__ + "." + id
obj = self.__objects.get(key)
return obj

def count(self, cls=None):
"""Count the number of objects in storage matching the given class.
If no class is passed, return the count of all objects in storage."""
if cls:
all_objs = self.all(cls)
count = len(all_objs)
else:
count = len(self.__objects)
return count

def new(self, obj):
"""sets in __objects the obj with key <obj class name>.id"""
if obj is not None:
Expand All @@ -55,7 +72,7 @@ def reload(self):
jo = json.load(f)
for key in jo:
self.__objects[key] = classes[jo[key]["__class__"]](**jo[key])
except:
except json.JSONDecodeError:
pass

def delete(self, obj=None):
Expand Down
12 changes: 12 additions & 0 deletions test_get_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/python3
""" Test .get() and .count() methods
"""
from models import storage
from models.state import State

print("All objects: {}".format(storage.count()))
print("State objects: {}".format(storage.count(State)))

first_state_id = list(storage.all(State).values())[0].id
print(first_state_id)
print("First state: {}".format(storage.get(State, first_state_id)))
8 changes: 4 additions & 4 deletions tests/test_models/test_base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,14 @@ def test_datetime_attributes(self):
"""Test that two BaseModel instances have different datetime objects
and that upon creation have identical updated_at and created_at
value."""
tic = datetime.now()
tic = datetime.utcnow()
inst1 = BaseModel()
toc = datetime.now()
toc = datetime.utcnow()
self.assertTrue(tic <= inst1.created_at <= toc)
time.sleep(1e-4)
tic = datetime.now()
tic = datetime.utcnow()
inst2 = BaseModel()
toc = datetime.now()
toc = datetime.utcnow()
self.assertTrue(tic <= inst2.created_at <= toc)
self.assertEqual(inst1.created_at, inst1.updated_at)
self.assertEqual(inst2.created_at, inst2.updated_at)
Expand Down
31 changes: 31 additions & 0 deletions tests/test_models/test_engine/test_file_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,37 @@ def test_new(self):
self.assertEqual(test_dict, storage._FileStorage__objects)
FileStorage._FileStorage__objects = save

@unittest.skipIf(models.storage_t == 'db', "not testing file storage")
def test_get(self):
"""Test the get method to retrieve an object by class and id"""
storage = FileStorage()
# Save the original __objects attribute and reset it
save = FileStorage._FileStorage__objects
FileStorage._FileStorage__objects = {}
test_state = State()
storage.new(test_state)
retrieved_obj = storage.get(State, test_state.id)
self.assertEqual(retrieved_obj, test_state)
non_existing_obj = storage.get(State, "n234-000o4-4")
self.assertIsNone(non_existing_obj)
FileStorage._FileStorage__objects = save

@unittest.skipIf(models.storage_t == 'db', "not testing file storage")
def test_count(self):
"""Test the get method to retrieve an object by class and id"""
storage = FileStorage()
objs = FileStorage._FileStorage__objects
FileStorage._FileStorage__objects = {}
test_state = State()
test_city = City()
storage.new(test_state)
storage.new(test_city)
count = storage.count()
count_state = storage.count(State)
self.assertEqual(count, 2)
self.assertEqual(count_state, 1)
FileStorage._FileStorage__objects = objs

@unittest.skipIf(models.storage_t == 'db', "not testing file storage")
def test_save(self):
"""Test that save properly saves objects to file.json"""
Expand Down