forked from justinmajetich/AirBnB_clone
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8b7209f
commit 369fe30
Showing
2 changed files
with
53 additions
and
139 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,86 +1,83 @@ | ||
#!/usr/bin/python3 | ||
"""This module defines a class to manage db storage for hbnb clone""" | ||
"""Defines a new engine that uses SQLAlchemy""" | ||
import os | ||
from sqlalchemy import create_engine | ||
from sqlalchemy.orm import sessionmaker, scoped_session | ||
from ..base_model import Base, BaseModel | ||
from os import getenv | ||
from sqlalchemy import create_engine, inspect | ||
|
||
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_MYSQL_PORT = getenv('HBNB_MYSQL_PORT') | ||
HBNB_ENV = 'dev' | ||
|
||
|
||
class DBStorage: | ||
"""This class manages storage of hbnb . in database""" | ||
"""DBStorage Engine running on SQLAlchemy""" | ||
|
||
__engine = None | ||
__session = None | ||
|
||
def __init__(self): | ||
"""initializes the database""" | ||
self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}' | ||
.format(HBNB_MYSQL_USER, HBNB_MYSQL_PWD, | ||
HBNB_MYSQL_HOST, HBNB_MYSQL_DB), | ||
pool_pre_ping=True) | ||
if HBNB_ENV == 'test': | ||
"""class constructor for DBStorage""" | ||
|
||
credentials = ['HBNB_MYSQL_USER', 'HBNB_MYSQL_PWD', | ||
'HBNB_MYSQL_HOST', 'HBNB_MYSQL_DB'] | ||
env = [os.environ.get(c) for c in credentials] | ||
e = 'mysql+mysqldb://{}:{}@{}/{}'.format(*env[:]) | ||
self.__engine = create_engine(e, pool_pre_ping=True) | ||
# Session = sessionmaker(bind=self.__engine) | ||
# self.__session = Session() | ||
|
||
# drop all tables if the environment variable | ||
# HBNB_ENV is equal to test | ||
if os.environ.get('HBNB_ENV') == 'test': | ||
from models.base_model import Base | ||
Base.metadata.drop_all(self.__engine) | ||
|
||
def all(self, cls=None): | ||
"""Returns a dictionary of all instances of a given class""" | ||
from ..user import User | ||
from ..state import State | ||
from ..city import City | ||
from ..place import Place | ||
from ..review import Review | ||
from ..amenity import Amenity | ||
"""Queries the current database session (self.__session) | ||
for all objects depending of the class name (argument cls)""" | ||
from models.user import User | ||
from models.state import State | ||
from models.city import City | ||
from models.amenity import Amenity | ||
from models.place import Place | ||
from models.review import Review | ||
|
||
result_dict = {} | ||
for model in [User, State, City, Place, Amenity, Review]: | ||
if cls is not None and model != cls: | ||
continue | ||
query_results = self.__session.query(model).all() | ||
for obj in query_results: | ||
key = "{}.{}".format(type(obj).__name__, obj.id) | ||
result_dict[key] = obj | ||
return result_dict | ||
class_list = [State, City, User, Place, Review, Amenity] | ||
objs = {} | ||
if cls is not None: | ||
for obj in self.__session.query(cls).all(): | ||
objs.update({obj.to_dict()['__class__'] + '.' + obj.id: obj}) | ||
else: | ||
for class_item in class_list: | ||
for obj in self.__session.query(class_item).all(): | ||
key = obj.to_dict()['__class__'] + '.' + obj.id | ||
objs.update({key: obj}) | ||
return objs | ||
|
||
def new(self, obj): | ||
"""Adds new object to storage dictionary""" | ||
if obj: | ||
try: | ||
self.__session.add(obj) | ||
self.__session.flush() | ||
self.__session.refresh(obj) | ||
except Exception: | ||
self.__session.rollback() | ||
"""Add obj to the current database session""" | ||
self.__session.add(obj) | ||
|
||
def save(self): | ||
"""Saves storage dictionary to file""" | ||
"""Commit all changes of the current database session""" | ||
self.__session.commit() | ||
|
||
def delete(self, obj=None): | ||
"""delete obj from __objects if it’s inside""" | ||
"""Delete from the current database session obj if not None""" | ||
if obj is not None: | ||
self.__session.delete(obj) | ||
|
||
def reload(self): | ||
"""Loads storage dictionary from file""" | ||
from ..user import User | ||
from ..state import State | ||
from ..city import City | ||
from ..place import Place | ||
from ..review import Review | ||
from ..amenity import Amenity | ||
"""Create all tables in the database | ||
""" | ||
from models.user import User | ||
from models.state import State | ||
from models.city import City | ||
from models.amenity import Amenity | ||
from models.place import Place | ||
from models.review import Review | ||
from models.base_model import Base | ||
|
||
Base.metadata.create_all(self.__engine) | ||
session_factory = sessionmaker( | ||
bind=self.__engine, expire_on_commit=False) | ||
self.__session = scoped_session(session_factory)() | ||
Session = sessionmaker(bind=self.__engine, expire_on_commit=False) | ||
self.__session = scoped_session(Session) | ||
|
||
def close(self): | ||
"""calls remove() method on the private | ||
session attribute (self.__session)""" | ||
"""call close() method for commiting objects to db""" | ||
self.__session.close() |
This file was deleted.
Oops, something went wrong.