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

Honorine dev #1467

Open
wants to merge 7 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
5 changes: 5 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
HBNB_MYSQL_USER = mysql
HBNB_MYSQL_PWD = Password@123!
HBNB_MYSQL_DB = hbnb_dev_db
HBNB_MYSQL_HOST = localhost
HBNB_ENV = test
3 changes: 3 additions & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@

Ezra Nobrega <[email protected]>
Justin Majetich <[email protected]>

Honorine Igiraneza <[email protected]>
Desmond Tunyinko <[email protected]>
151 changes: 114 additions & 37 deletions console.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
""" Console Module """
import cmd
import sys
import models
from models.base_model import BaseModel
from models.__init__ import storage
from models.user import User
from models.place import Place
from models.state import State
Expand All @@ -13,22 +13,65 @@


class HBNBCommand(cmd.Cmd):
""" Contains the functionality for the HBNB console"""
"""Command interpreter for the HBNB project

# determines prompt for interactive/non-interactive modes

**CMD MODULE CONVENTION**


The cmd module in Python provides a framework for writing
line-oriented command interpreters. It provides a base class, cmd.Cmd,
that defines methods and attributes for creating a command-line interface.

Conventions followed by the cmd module:

Command methods must start with the prefix ``do_``

*Examples:*\n
``do_quit()`` will run the command ``quit`` \n
``do_foo()`` will run the command ``foo``

\n

Help methods must start with the prefix ``help_``

*Examples:*\n
``help_quit()`` will run the command ``help quit`` \n
``help_save()`` will run the command ``help save``

The ``emptyline()`` method is called when an empty line is entered in the
command prompt. By default, it repeats the last non-empty command entered.
However, it can be overridden to perform a different action or pass.

The ``EOF`` command (or Ctrl-D) is handled by the ``do_EOF()`` method,
which by default exits the command interpreter.

The ``quit`` command is handled by the ``do_quit()`` method,
which by default exits the command interpreter.

The ``help`` command is handled by the ``do_help()`` method,
which by default lists all available commands and their brief descriptions.

More information can be found in the official documentation on
[cmd source code](https://github.com/python/cpython/blob/3.11/Lib/cmd.py)
"""

# prints (hbnb) if the script is running in a terminal otherwise ''
prompt = '(hbnb) ' if sys.__stdin__.isatty() else ''

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

dot_cmds = ['all', 'count', 'show', 'destroy', 'update']

types = {
'number_rooms': int, 'number_bathrooms': int,
'max_guest': int, 'price_by_night': int,
'latitude': float, 'longitude': float
}
'number_rooms': int, 'number_bathrooms': int,
'max_guest': int, 'price_by_night': int,
'latitude': float, 'longitude': float
}

def preloop(self):
"""Prints if isatty is false"""
Expand All @@ -43,7 +86,7 @@ def precmd(self, line):
"""
_cmd = _cls = _id = _args = '' # initialize line elements

# scan for general formating - i.e '.', '(', ')'
# scan for general formatting - i.e '.', '(', ')'
if not ('.' in line and '(' in line and ')' in line):
return line

Expand All @@ -58,7 +101,7 @@ def precmd(self, line):
if _cmd not in HBNBCommand.dot_cmds:
raise Exception

# if parantheses contain arguments, parse them
# if parentheses contain arguments, parse them
pline = pline[pline.find('(') + 1:pline.find(')')]
if pline:
# partition args: (<id>, [<delim>], [<*args>])
Expand All @@ -73,7 +116,7 @@ def precmd(self, line):
pline = pline[2].strip() # pline is now str
if pline:
# check for *args or **kwargs
if pline[0] is '{' and pline[-1] is'}'\
if pline[0] == '{' and pline[-1] == '}' \
and type(eval(pline)) is dict:
_args = pline
else:
Expand Down Expand Up @@ -115,16 +158,43 @@ def emptyline(self):

def do_create(self, args):
""" Create an object of any class"""
if not args:
if len(args) < 1:
print("** class name missing **")
return
elif args not in HBNBCommand.classes:
# convert the args to a list
args = args.split()

# the 1st element of the list is the class name
class_name = args[0]

if class_name not in self.classes:
print("** class doesn't exist **")
return
new_instance = HBNBCommand.classes[args]()
storage.save()
new_instance = self.classes[class_name]()
for params in args[1:]:
if "=" not in params:
continue
key, value = params.split('=')
value = value.replace('_', ' ')
if value.startswith('"') and value.endswith('"'):
value = value[1:-1].replace('\\"', '"')
elif '.' in value:
try:
value = float(value)
except ValueError:
continue
else:
try:
value = int(value)
except ValueError:
continue

if value is not None and value != "" and hasattr(
new_instance, key):
setattr(new_instance, key, value)

print(new_instance.id)
storage.save()
new_instance.save()

def help_create(self):
""" Help information for the create method """
Expand Down Expand Up @@ -155,7 +225,7 @@ def do_show(self, args):

key = c_name + "." + c_id
try:
print(storage._FileStorage__objects[key])
print(models.storage.all()[key])
except KeyError:
print("** no instance found **")

Expand All @@ -176,7 +246,7 @@ def do_destroy(self, args):
print("** class name missing **")
return

if c_name not in HBNBCommand.classes:
if c_name not in self.classes:
print("** class doesn't exist **")
return

Expand All @@ -187,8 +257,8 @@ def do_destroy(self, args):
key = c_name + "." + c_id

try:
del(storage.all()[key])
storage.save()
del (models.storage.all()[key])
models.storage.save()
except KeyError:
print("** no instance found **")

Expand All @@ -202,15 +272,15 @@ def do_all(self, args):
print_list = []

if args:
args = args.split(' ')[0] # remove possible trailing args
if args not in HBNBCommand.classes:
class_name = args.split()[0]
if class_name not in self.classes:
print("** class doesn't exist **")
return
for k, v in storage._FileStorage__objects.items():
if k.split('.')[0] == args:
for k, v in models.storage.all().items():
if k.split('.')[0] == class_name:
print_list.append(str(v))
else:
for k, v in storage._FileStorage__objects.items():
for k, v in models.storage.all().items():
print_list.append(str(v))

print(print_list)
Expand All @@ -223,7 +293,7 @@ def help_all(self):
def do_count(self, args):
"""Count current number of class instances"""
count = 0
for k, v in storage._FileStorage__objects.items():
for k, v in models.storage._FileStorage__objects.items():
if args == k.split('.')[0]:
count += 1
print(count)
Expand All @@ -243,7 +313,7 @@ def do_update(self, args):
else: # class name not present
print("** class name missing **")
return
if c_name not in HBNBCommand.classes: # class name invalid
if c_name not in self.classes: # class name invalid
print("** class doesn't exist **")
return

Expand All @@ -259,7 +329,7 @@ def do_update(self, args):
key = c_name + "." + c_id

# determine if key is present
if key not in storage.all():
if key not in models.storage.all():
print("** no instance found **")
return

Expand All @@ -272,18 +342,18 @@ def do_update(self, args):
args.append(v)
else: # isolate args
args = args[2]
if args and args[0] is '\"': # check for quoted arg
if args and args[0] == '\"': # check for quoted arg
second_quote = args.find('\"', 1)
att_name = args[1:second_quote]
args = args[second_quote + 1:]

args = args.partition(' ')

# if att_name was not quoted arg
if not att_name and args[0] is not ' ':
if not att_name and args[0] != ' ':
att_name = args[0]
# check for quoted val arg
if args[2] and args[2][0] is '\"':
if args[2] and args[2][0] == '\"':
att_val = args[2][1:args[2].find('\"', 1)]

# if att_val was not quoted arg
Expand All @@ -293,7 +363,7 @@ def do_update(self, args):
args = [att_name, att_val]

# retrieve dictionary of current objects
new_dict = storage.all()[key]
new_dict = models.storage.all()[key]

# iterate through attr names and values
for i, att_name in enumerate(args):
Expand All @@ -307,8 +377,8 @@ def do_update(self, args):
print("** value missing **")
return
# type cast as necessary
if att_name in HBNBCommand.types:
att_val = HBNBCommand.types[att_name](att_val)
if att_name in self.types:
att_val = self.types[att_name](att_val)

# update dictionary with name, value pair
new_dict.__dict__.update({att_name: att_val})
Expand All @@ -320,5 +390,12 @@ def help_update(self):
print("Updates an object with new information")
print("Usage: update <className> <id> <attName> <attVal>\n")


if __name__ == "__main__":
"""
Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
(see: https://github.com/python/cpython/blob/3.8/Lib/cmd.py#L98)
"""
HBNBCommand().cmdloop()
84 changes: 84 additions & 0 deletions models/engine/db_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/usr/bin/python3
""" new class for sqlAlchemy """
from os import getenv
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import (create_engine)
from sqlalchemy.ext.declarative import declarative_base
from models.base_model import Base
from models.state import State
from models.city import City
from models.user import User
from models.place import Place
from models.review import Review
from models.amenity import Amenity


class DBStorage:
""" create tables in environmental"""
__engine = None
__session = None

def __init__(self):
user = getenv("HBNB_MYSQL_USER")
passwd = getenv("HBNB_MYSQL_PWD")
db = getenv("HBNB_MYSQL_DB")
host = getenv("HBNB_MYSQL_HOST")
env = getenv("HBNB_ENV")

self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'
.format(user, passwd, host, db),
pool_pre_ping=True)

if env == "test":
Base.metadata.drop_all(self.__engine)

def all(self, cls=None):
"""returns a dictionary
Return:
returns a dictionary of __object
"""
dic = {}
if cls:
if isinstance(cls, str):
cls = eval(cls)
query = self.__session.query(cls)
for elem in query:
key = "{}.{}".format(type(elem).__name__, elem.id)
dic[key] = elem
else:
lista = [State, City, User, Place, Review, Amenity]
for clase in lista:
query = self.__session.query(clase)
for elem in query:
key = "{}.{}".format(type(elem).__name__, elem.id)
dic[key] = elem
return (dic)

def new(self, obj):
"""add a new element in the table
"""
self.__session.add(obj)

def save(self):
"""save changes
"""
self.__session.commit()

def delete(self, obj=None):
"""delete an element in the table
"""
if obj:
self.session.delete(obj)

def reload(self):
"""configuration
"""
Base.metadata.create_all(self.__engine)
sec = sessionmaker(bind=self.__engine, expire_on_commit=False)
Session = scoped_session(sec)
self.__session = Session()

def close(self):
""" calls remove()
"""
self.__session.close()
Loading