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 #3720

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
3 changes: 2 additions & 1 deletion 1-pack_web_static.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ def do_pack():
file_name = "versions/web_static_{}.tgz".format(date)
local("tar -cvzf {} web_static".format(file_name))
return file_name
except:
except Exception as e:
print(f"error: {e}")
return None
3 changes: 2 additions & 1 deletion 2-do_deploy_web_static.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@ def do_deploy(archive_path):
run('rm -rf /data/web_static/current')
run('ln -s {}{}/ /data/web_static/current'.format(path, no_ext))
return True
except:
except Exception as e:
print(f"error: {e}")
return False
6 changes: 4 additions & 2 deletions 3-deploy_web_static.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ def do_pack():
file_name = "versions/web_static_{}.tgz".format(date)
local("tar -cvzf {} web_static".format(file_name))
return file_name
except:
except Exception as e:
print(f"error: {e}")
return None


Expand All @@ -40,7 +41,8 @@ def do_deploy(archive_path):
run('rm -rf /data/web_static/current')
run('ln -s {}{}/ /data/web_static/current'.format(path, no_ext))
return True
except:
except Exception as e:
print(f"error: {e}")
return False


Expand Down
3 changes: 2 additions & 1 deletion AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@

Jennifer Huang <[email protected]>
Alexa Orrico <[email protected]>
Joann Vuong <[email protected]>
Joann Vuong <[email protected]>
Joana Casallas <[email protected]>
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# AirBnB Clone - The Console
The console is the first segment of the AirBnB project at Holberton School that will collectively cover fundamental concepts of higher level programming. The goal of AirBnB project is to eventually deploy our server a simple copy of the AirBnB Website(HBnB). A command interpreter is created in this segment to manage objects for the AirBnB(HBnB) website.
# AirBnB clone - RESTful API
The goal of AirBnB project is to eventually deploy our server a simple copy of the AirBnB Website(HBnB). A command interpreter is created in this segment to manage objects for the AirBnB(HBnB) website.

We will have a complete web application composed by:

* A command interpreter to manipulate data without a visual interface, like in a Shell (perfect for development and debugging)
* A website (the front-end) that shows the final product to everybody: static and dynamic
* A database or files that store data (data = objects)
* An API that provides a communication interface between the front-end and your data (retrieve, create, delete, update them)


#### Functionalities of this command interpreter:
* Create a new object (ex: a new User or a new Place)
Expand All @@ -8,6 +16,11 @@ The console is the first segment of the AirBnB project at Holberton School that
* Update attributes of an object
* Destroy an object

#### RESTful API:
* Expose all your objects stored via a JSON web interface
* Manipulate your objects via a RESTful API


## Table of Content
* [Environment](#environment)
* [Installation](#installation)
Expand Down Expand Up @@ -156,6 +169,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)
Joana Casallas - [Github](https://github.com/joacasallas2) / [Twitter](https://twitter.com/joanacasallas)

Second part of Airbnb: Joann Vuong
## License
Expand Down
Binary file added __pycache__/console.cpython-312.pyc
Binary file not shown.
Empty file added api/__init__.py
Empty file.
Binary file added api/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Empty file added api/v1/__init__.py
Empty file.
Binary file added api/v1/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file added api/v1/__pycache__/app.cpython-312.pyc
Binary file not shown.
25 changes: 25 additions & 0 deletions api/v1/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/usr/bin/python3
# Author: Joana Casallas
"""Flask App"""
import os
from flask import Flask
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):
"""Remove the current SQLAlchemy session after each request"""
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)
9 changes: 9 additions & 0 deletions api/v1/views/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/python3
# Author: Joana Casallas
"""Blueprint app_views"""
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound


app_views = Blueprint('app_views', __name__, url_prefix='/api/v1')
from api.v1.views.index import * # noqa: F401
Binary file added api/v1/views/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file added api/v1/views/__pycache__/index.cpython-312.pyc
Binary file not shown.
Empty file added api/v1/views/amenities.py
Empty file.
Empty file added api/v1/views/cities.py
Empty file.
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
# Author: Joana Casallas
"""Index API"""
from flask import jsonify
from api.v1.views import app_views


@app_views.route('/status', methods=['GET'])
def status():
"""Return API status"""
return jsonify({"status": "OK"})
Empty file added api/v1/views/places.py
Empty file.
Empty file added api/v1/views/states.py
Empty file.
Empty file added api/v1/views/users.py
Empty file.
9 changes: 5 additions & 4 deletions console.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ def _key_value_parser(self, args):
else:
try:
value = int(value)
except:
except ValueError:
try:
value = float(value)
except:
except ValueError:
continue
new_dict[key] = value
return new_dict
Expand Down Expand Up @@ -140,12 +140,12 @@ def do_update(self, arg):
if args[2] in integers:
try:
args[3] = int(args[3])
except:
except ValueError:
args[3] = 0
elif args[2] in floats:
try:
args[3] = float(args[3])
except:
except ValueError:
args[3] = 0.0
setattr(models.storage.all()[k], args[2], args[3])
models.storage.all()[k].save()
Expand All @@ -160,5 +160,6 @@ def do_update(self, arg):
else:
print("** class doesn't exist **")


if __name__ == '__main__':
HBNBCommand().cmdloop()
44 changes: 44 additions & 0 deletions file.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"Amenity.1d4df609-a0e2-4bc9-9f80-3f6835e4fb24": {
"id": "1d4df609-a0e2-4bc9-9f80-3f6835e4fb24",
"created_at": "2025-02-07T23:25:06.682825",
"updated_at": "2025-02-07T23:25:06.682825",
"__class__": "Amenity"
},
"BaseModel.5a961649-9ec0-4785-a7ea-4e19225a714c": {
"id": "5a961649-9ec0-4785-a7ea-4e19225a714c",
"created_at": "2025-02-07T23:25:06.682832",
"updated_at": "2025-02-07T23:25:06.682832",
"__class__": "BaseModel"
},
"City.6f316a8d-3233-4bc8-9c30-e0a6280cf55d": {
"id": "6f316a8d-3233-4bc8-9c30-e0a6280cf55d",
"created_at": "2025-02-07T23:25:06.682838",
"updated_at": "2025-02-07T23:25:06.682838",
"__class__": "City"
},
"Place.e5becbd2-1fff-41f2-86b4-188dbe114339": {
"id": "e5becbd2-1fff-41f2-86b4-188dbe114339",
"created_at": "2025-02-07T23:25:06.682843",
"updated_at": "2025-02-07T23:25:06.682843",
"__class__": "Place"
},
"Review.f2499d20-591b-48e0-9af1-b29c87ce5130": {
"id": "f2499d20-591b-48e0-9af1-b29c87ce5130",
"created_at": "2025-02-07T23:25:06.682847",
"updated_at": "2025-02-07T23:25:06.682847",
"__class__": "Review"
},
"State.ee8b31c8-a441-4aae-9ac8-4b9c0d43d443": {
"id": "ee8b31c8-a441-4aae-9ac8-4b9c0d43d443",
"created_at": "2025-02-07T23:25:06.682851",
"updated_at": "2025-02-07T23:25:06.682851",
"__class__": "State"
},
"User.db482086-a82a-46dd-808c-34d970c7015f": {
"id": "db482086-a82a-46dd-808c-34d970c7015f",
"created_at": "2025-02-07T23:25:06.682855",
"updated_at": "2025-02-07T23:25:06.682855",
"__class__": "User"
}
}
Binary file added models/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file added models/__pycache__/amenity.cpython-312.pyc
Binary file not shown.
Binary file added models/__pycache__/base_model.cpython-312.pyc
Binary file not shown.
Binary file added models/__pycache__/city.cpython-312.pyc
Binary file not shown.
Binary file added models/__pycache__/place.cpython-312.pyc
Binary file not shown.
Binary file added models/__pycache__/review.cpython-312.pyc
Binary file not shown.
Binary file added models/__pycache__/state.cpython-312.pyc
Binary file not shown.
Binary file added models/__pycache__/user.cpython-312.pyc
Binary file not shown.
21 changes: 12 additions & 9 deletions models/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
Contains class BaseModel
"""

from datetime import datetime
import models
from datetime import datetime, timezone
from os import getenv
import sqlalchemy
from sqlalchemy import Column, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
import uuid
import models

time = "%Y-%m-%dT%H:%M:%S.%f"

Expand All @@ -23,8 +23,10 @@ class BaseModel:
"""The BaseModel class from which future classes will be derived"""
if models.storage_t == "db":
id = Column(String(60), primary_key=True)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow)
created_at = Column(
DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(
DateTime, default=lambda: datetime.now(timezone.utc))

def __init__(self, *args, **kwargs):
"""Initialization of the base model"""
Expand All @@ -35,16 +37,17 @@ def __init__(self, *args, **kwargs):
if kwargs.get("created_at", None) and type(self.created_at) is str:
self.created_at = datetime.strptime(kwargs["created_at"], time)
else:
self.created_at = datetime.utcnow()
self.created_at = datetime.now(timezone.utc)
if kwargs.get("updated_at", None) and type(self.updated_at) is str:
self.updated_at = datetime.strptime(kwargs["updated_at"], time)
self.updated_at = datetime.strptime(
kwargs["updated_at"], time).replace(tzinfo=timezone.utc)
else:
self.updated_at = datetime.utcnow()
self.updated_at = datetime.now(timezone.utc)
if kwargs.get("id", None) is None:
self.id = str(uuid.uuid4())
else:
self.id = str(uuid.uuid4())
self.created_at = datetime.utcnow()
self.created_at = datetime.now(timezone.utc)
self.updated_at = self.created_at

def __str__(self):
Expand All @@ -54,7 +57,7 @@ def __str__(self):

def save(self):
"""updates the attribute 'updated_at' with the current datetime"""
self.updated_at = datetime.utcnow()
self.updated_at = datetime.now(timezone.utc)
models.storage.new(self)
models.storage.save()

Expand Down
Binary file added models/engine/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
30 changes: 24 additions & 6 deletions models/engine/db_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,16 @@
Contains the class DBStorage
"""

import models
from os import getenv
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from models.amenity import Amenity
from models.base_model import BaseModel, Base
from models.base_model import Base
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.user import User
from os import getenv
import sqlalchemy
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}
Expand Down Expand Up @@ -74,3 +72,23 @@ 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"""
for clss in classes:
if cls is classes[clss] or cls is clss:
objs = self.__session.query(classes[clss]).all()
for obj in objs:
if id == obj.id:
return (obj)
return None

def count(self, cls=None):
"""count the number of objects in storage"""
count = 0
for clss in classes:
if cls is None or cls is classes[clss] or cls is clss:
objs = self.__session.query(classes[clss]).all()
for obj in objs:
count += 1
return (count)
35 changes: 34 additions & 1 deletion models/engine/file_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ def reload(self):
jo = json.load(f)
for key in jo:
self.__objects[key] = classes[jo[key]["__class__"]](**jo[key])
except:
except FileNotFoundError:
pass
except json.JSONDecodeError as e:
print(f"Error loading JSON file: {e}")

def delete(self, obj=None):
"""delete obj from __objects if it’s inside"""
Expand All @@ -68,3 +70,34 @@ def delete(self, obj=None):
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"""
if isinstance(cls, str):
clss = classes[cls]
else:
clss = cls.__name__

for k, v in self.__objects.items():
class_name = k.split(".")[0]
class_id = k.split(".")[1]
if class_name == clss and class_id == id:
return v
return None

def count(self, cls=None):
"""count the number of objects in storage"""
dict_classes = {}
count = 0
if cls is None:
dict_classes = classes
else:
if isinstance(cls, str):
dict_classes = classes[cls]
else:
dict_classes = cls.__name__

for obj in self.__objects:
if obj.split(".")[0] in dict_classes:
count += 1
return count
11 changes: 11 additions & 0 deletions test_get_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/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: {}".format(storage.get(State, first_state_id)))
Binary file added tests/__pycache__/test_console.cpython-312.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.
Loading