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

docs: add author #1473

Open
wants to merge 41 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
cb19e79
Add new author
NsengaNigel Sep 25, 2024
4a173a1
v2 clone
NsengaNigel Sep 25, 2024
4acf3cd
models v2
NsengaNigel Sep 25, 2024
46421f6
tests v2
NsengaNigel Sep 25, 2024
f42734a
Console v2
NsengaNigel Sep 25, 2024
58eab35
console v2
NsengaNigel Sep 25, 2024
590eb03
console v2
NsengaNigel Sep 25, 2024
395b44c
console v2
NsengaNigel Sep 25, 2024
d944d38
My sql v2
NsengaNigel Sep 25, 2024
21d2966
my sql test
NsengaNigel Sep 25, 2024
2b9d22d
Add models v2
NsengaNigel Sep 25, 2024
0a70fc8
Add models v2
NsengaNigel Sep 25, 2024
e874ee5
models v2
NsengaNigel Sep 25, 2024
3898f05
Tests v2
NsengaNigel Sep 25, 2024
f9122dd
Update base model
NsengaNigel Sep 25, 2024
cc13025
city v2
NsengaNigel Sep 25, 2024
4501fb7
state v2
NsengaNigel Sep 25, 2024
7ba6003
db v2
NsengaNigel Sep 25, 2024
c3f76ba
init v2
NsengaNigel Sep 25, 2024
09b9d1e
city v2
NsengaNigel Sep 25, 2024
962616c
state v2
NsengaNigel Sep 25, 2024
541eee6
city v2
NsengaNigel Sep 25, 2024
f5a8637
storage v2
NsengaNigel Sep 25, 2024
8a2d2e1
user v2
NsengaNigel Sep 25, 2024
c536066
user v2
NsengaNigel Sep 25, 2024
d4f552b
place v2
NsengaNigel Sep 25, 2024
e28d395
user v2
NsengaNigel Sep 25, 2024
df25a7f
city v2
NsengaNigel Sep 25, 2024
c7526c8
place v2
NsengaNigel Sep 25, 2024
831a69d
user v2
NsengaNigel Sep 25, 2024
7c4bbf9
city v2
NsengaNigel Sep 25, 2024
afb1392
review v2
NsengaNigel Sep 25, 2024
ea2f2fd
models/user.py
NsengaNigel Sep 25, 2024
90fa822
place v2
NsengaNigel Sep 25, 2024
62b164e
console v2
NsengaNigel Sep 25, 2024
3512037
amenity v2
NsengaNigel Sep 25, 2024
ab3a5a3
place v2
NsengaNigel Sep 25, 2024
667a84a
place v2
NsengaNigel Sep 25, 2024
4db9f15
fix: fix all issues
claranceliberi Sep 27, 2024
095e10c
feat: use any python3 availabe in env
claranceliberi Sep 27, 2024
cb29545
docs: add author
claranceliberi Sep 27, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# ignore all .pyc files
*.pyc
2 changes: 2 additions & 0 deletions AUTHORS
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@

Ezra Nobrega <[email protected]>
Justin Majetich <[email protected]>
Nsenga Nigel <[email protected]>
Clarance Liberi <[email protected]>
Empty file modified README.md
100644 → 100755
Empty file.
217 changes: 89 additions & 128 deletions console.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/python3
#!/usr/bin/env python3
""" Console Module """
import cmd
import sys
Expand All @@ -15,20 +15,22 @@
class HBNBCommand(cmd.Cmd):
""" Contains the functionality for the HBNB console"""

# determines prompt for interactive/non-interactive modes
prompt = '(hbnb) ' if sys.__stdin__.isatty() else ''
# Determines prompt for interactive/non-interactive modes
prompt = '(hbnb) ' if sys.__stdin__ and sys.__stdin__.isatty() else ''

classes = {
'BaseModel': BaseModel, 'User': User, 'Place': Place,
'State': State, 'City': City, 'Amenity': Amenity,
'Review': Review
}
dot_cmds = ['all', 'count', 'show', 'destroy', 'update']
'BaseModel': BaseModel, 'User': User, 'Place': Place,
'State': State, 'City': City, 'Amenity': Amenity,
'Review': Review
}

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

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 @@ -37,13 +39,12 @@ def preloop(self):

def precmd(self, line):
"""Reformat command line for advanced command syntax.

Usage: <class name>.<command>([<id> [<*args> or <**kwargs>]])
(Brackets denote optional fields in usage example.)
"""
_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,27 +59,24 @@ 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>])
pline = pline.partition(', ') # pline convert to tuple

# isolate _id, stripping quotes
_id = pline[0].replace('\"', '')
# possible bug here:
# empty quotes register as empty _id when replaced

# if arguments exist beyond _id
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:
_args = pline.replace(',', '')
# _args = _args.replace('\"', '')
line = ' '.join([_cmd, _cls, _id, _args])

except Exception as mess:
Expand Down Expand Up @@ -110,26 +108,89 @@ def help_EOF(self):
print("Exits the program without formatting\n")

def emptyline(self):
""" Overrides the emptyline method of CMD """
pass
""" Overrides the emptyline method of CMD """
return False
pass

def do_create(self, args):
""" Create an object of any class"""
args = args.strip().split(' ')
if not args:
print("** class name missing **")
return
elif args not in HBNBCommand.classes:
class_name = args[0]
if class_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
new_instance = HBNBCommand.classes[args]()
storage.save()

# Create instance with provided attributes
new_instance = HBNBCommand.classes[class_name]()
if class_name == "Review":
place_id = None
user_id = None
text = None
for arg in args[1:]:
if '=' in arg:
key, value = arg.split('=')
key = key.strip()
value = value.strip().strip('"')

# Convert spaces to underscores in the key
key = key.replace(' ', '_')

# Check for required fields in Review
if key == "place_id":
place_id = value
elif key == "user_id":
user_id = value
elif key == "text":
text = value

# Validation logic for Review creation
if place_id is None or user_id is None or text is None:
print("** place_id, user_id, and text must be provided **")
return

# Check if the place_id and user_id are valid (exist in the database)
if not self.valid_id(Place, place_id):
print("** place_id doesn't exist **")
return
if not self.valid_id(User, user_id):
print("** user_id doesn't exist **")
return

# Set other attributes
for arg in args[1:]:
if '=' in arg:
key, value = arg.split('=')
key = key.strip()
value = value.strip().strip('"')

# Convert spaces to underscores in the key
key = key.replace(' ', '_')

# Cast value to appropriate type if it is specified
if key in HBNBCommand.types:
try:
value = HBNBCommand.types[key](value)
except ValueError:
print(f"** invalid value for {key} **")
return

setattr(new_instance, key, value)

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

def valid_id(self, class_name, obj_id):
""" Checks if an ID exists for a given class """
key = f"{class_name.__name__}.{obj_id}"
return key in storage.all()

def help_create(self):
""" Help information for the create method """
print("Creates a class of any type")
print("[Usage]: create <className>\n")
print("[Usage]: create <className> <attribute=value> ...\n")

def do_show(self, args):
""" Method to show an individual object """
Expand Down Expand Up @@ -220,105 +281,5 @@ def help_all(self):
print("Shows all objects, or all of a class")
print("[Usage]: all <className>\n")

def do_count(self, args):
"""Count current number of class instances"""
count = 0
for k, v in storage._FileStorage__objects.items():
if args == k.split('.')[0]:
count += 1
print(count)

def help_count(self):
""" """
print("Usage: count <class_name>")

def do_update(self, args):
""" Updates a certain object with new info """
c_name = c_id = att_name = att_val = kwargs = ''

# isolate cls from id/args, ex: (<cls>, delim, <id/args>)
args = args.partition(" ")
if args[0]:
c_name = args[0]
else: # class name not present
print("** class name missing **")
return
if c_name not in HBNBCommand.classes: # class name invalid
print("** class doesn't exist **")
return

# isolate id from args
args = args[2].partition(" ")
if args[0]:
c_id = args[0]
else: # id not present
print("** instance id missing **")
return

# generate key from class and id
key = c_name + "." + c_id

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

# first determine if kwargs or args
if '{' in args[2] and '}' in args[2] and type(eval(args[2])) is dict:
kwargs = eval(args[2])
args = [] # reformat kwargs into list, ex: [<name>, <value>, ...]
for k, v in kwargs.items():
args.append(k)
args.append(v)
else: # isolate args
args = args[2]
if args and args[0] is '\"': # 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 ' ':
att_name = args[0]
# check for quoted val arg
if args[2] and args[2][0] is '\"':
att_val = args[2][1:args[2].find('\"', 1)]

# if att_val was not quoted arg
if not att_val and args[2]:
att_val = args[2].partition(' ')[0]

args = [att_name, att_val]

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

# iterate through attr names and values
for i, att_name in enumerate(args):
# block only runs on even iterations
if (i % 2 == 0):
att_val = args[i + 1] # following item is value
if not att_name: # check for att_name
print("** attribute name missing **")
return
if not att_val: # check for att_value
print("** value missing **")
return
# type cast as necessary
if att_name in HBNBCommand.types:
att_val = HBNBCommand.types[att_name](att_val)

# update dictionary with name, value pair
new_dict.__dict__.update({att_name: att_val})

new_dict.save() # save updates to file

def help_update(self):
""" Help information for the update class """
print("Updates an object with new information")
print("Usage: update <className> <id> <attName> <attVal>\n")

if __name__ == "__main__":
HBNBCommand().cmdloop()
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 @@
{"BaseModel.(no name)": {"updated_at": "2024-09-27T13:11:46.440666", "created_at": "(no name)"}}
15 changes: 11 additions & 4 deletions models/__init__.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
#!/usr/bin/python3
"""This module instantiates an object of class FileStorage"""
from models.engine.file_storage import FileStorage
#!/usr/bin/env python3
"""Models Initialization Module."""

from os import getenv

if getenv('HBNB_TYPE_STORAGE') == 'db':
from models.engine.db_storage import DBStorage
storage = DBStorage()
else:
from models.engine.file_storage import FileStorage
storage = FileStorage()

storage = FileStorage()
storage.reload()

18 changes: 13 additions & 5 deletions models/amenity.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
#!/usr/bin/python3
""" State Module for HBNB project """
from models.base_model import BaseModel
#!/usr/bin/env python3
""" Module for Amenity class """
from models.base_model import Base, BaseModel
from sqlalchemy import Column, String
from sqlalchemy.orm import relationship


class Amenity(BaseModel):
name = ""
class Amenity(BaseModel, Base):
""" Amenity class for storage in database """
__tablename__ = 'amenities'

name = Column(String(128), nullable=False)

place_amenities = relationship("Place", secondary="place_amenity", back_populates="amenities")

Loading