Пример #1
0
    def do_show(self, args):
        """
           prints string reps of instance based on class name and ID
        """
        args = shlex.split(args)
        if len(args) == 0:
            print("** class name missing **")
            return
        if len(args) == 1:
            print("** instance id missing **")
            return
        storage = FileStorage()
        storage.reload()
        object_dict = storage.all()

        try:
            eval(args[0])
        except NameError:
            print("** class doesn't exist **")
            return
        keys = args[0] + "." + args[1]
        keys = args[0] + "." + args[1]
        try:
            Value = object_dict[keys]
            print(Value)
        except KeyError:
            print("** no instance found **")
Пример #2
0
    def do_show(self, arg):
        """Prints the string representation of an instance
        """
        arg = self.parse_arg(arg)

        if len(arg) == 0:
            print("** class name missing **")
            return
        elif len(arg) == 1:
            print("** instance id missing **")
            return

        class_in = arg[0]
        key_in = arg[1]

        is_class = False

        all_objs = storage.all()

        for index in all_objs.keys():
            if class_in in index.split(".")[0]:
                is_class = True
                if key_in in index.split(".")[1]:
                    print(str(all_objs[index]))
                    return

        if is_class is True:
            print("** no instance found **")
        else:
            print("** class doesn't exist **")
Пример #3
0
    def do_destroy(self, args):
        """ Destroys a specified object """
        new = args.partition(" ")
        c_name = new[0]
        c_id = new[2]
        if c_id and ' ' in c_id:
            c_id = c_id.partition(' ')[0]

        if not c_name:
            print("** class name missing **")
            return

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

        if not c_id:
            print("** instance id missing **")
            return

        key = c_name + "." + c_id

        try:
            del (storage.all()[key])
            storage.save()
        except KeyError:
            print("** no instance found **")
Пример #4
0
 def do_all(self, line):
     """ select all objects and return all attributes of NAME_OBJECT
     use 'all [NAME_OBJECT]' - NAME_OBJECT is any name of de object
     """
     # Get the argc and argv
     argv = line.split()
     argc = len(argv)
     # Load all the obects in instances
     instances = storage.all()
     # Verify if len of argc is equal to 0
     if argc == 0:
         # Create a empty list for all instances
         list_for_all = []
         for key, obj in instances.items():
             list_for_all.append(str(obj))
         print(list_for_all)
         return
     # Verify if class not exist in base
     if argv[0] not in base:
         print("** class doesn't exist **")
         return
     # If not - exist
     else:
         # Create new list
         new_list = []
         # Iterate in key and obj
         for key, obj in instances.items():
             # Example if BaseModel is the type of
             # type(obj).__name__ this is equal a
             # BaseModel
             if argv[0] == type(obj).__name__:
                 # Append the string of object
                 new_list.append(str(obj))
         # Print the new list
         print(new_list)
Пример #5
0
    def do_destroy(self, line):
        """Destroys an instance based on class name and ID"""

        args = split(line)
        if len(args) == 0:
            print("** class name missing **")
            return
        elif len(args) == 1:
            print("** instance id missing **")
            return
        clsName = args[0]
        clsId = args[1]
        storage = FileStorage()
        storage.reload()
        objDict = storage.all()

        try:
            eval(clsName)

        except NameError:
            print("** class doesn't exist **")
            return

        key = clsName + "." + clsId

        try:
            del objDict[key]

        except KeyError:
            print("** no instance found **")
        storage.save()
Пример #6
0
 def default(self, line):
     '''
     Advanced
     '''
     _cmd = storage.all()
     if '.' in line:
         cmd_parse = line.split('.')
         class_name = cmd_parse[0]
         method_name = cmd_parse[1]
         if class_name in Class_Dict:
             if method_name[0:5] == 'all()':
                 self.do_all(class_name)
             if method_name[0:7] == 'count()':
                 self.do_count(class_name)
             if method_name[0:5] == 'show(':
                 method_name2 = method_name.split('"')
                 show_id = method_name2[1]
                 arg = class_name + ' ' + show_id
                 print(arg)
                 self.do_show(arg)
             if method_name[0:8] == 'destroy(':
                 method_name2 = method_name.split('"')
                 show_id = method_name2[1]
                 arg = class_name + ' ' + show_id
                 self.do_destroy(arg)
             if method_name[0:7] == 'update(':
                 method_name2 = method_name.split('"')
                 show_id = method_name2[1]
                 show_att_name = method_name2[3]
                 show_att_val = method_name2[5]
                 arg = class_name + ' ' + show_id +\
                     ' ' + show_att_name + ' ' + show_att_val
                 print(arg)
                 self.do_update(arg)
Пример #7
0
 def do_destroy(self, line):
     """Delete an instance based on the class name and id
     use - 'destroy [NAME_OBJECT] [ID]'
     """
     # Splits line by the spaces
     argv = line.split()
     argc = len(argv)
     # if no arguments happen
     if argc == 0:
         print("** class name missing **")
         return
     if argv[0] not in base:
         print("** class doesn't exist **")
         return
     if argc == 1:
         print("** instance id missing **")
         return
     # Get all instances
     instances = storage.all()
     key_ref = argv[0] + "." + argv[1]
     if key_ref in instances.keys():
         del instances[key_ref]
         storage.save()
         return
         # if it does not exist
     else:
         print("** no instance found **")
Пример #8
0
    def do_update(self, args):
        'updates an instance attribute based on class name and id'
        args = args.split()
        if not args:
            print("** class name missing **")
            return
        elif len(args) < 2:
            print("** instance id missing **")
            return
        elif len(args) < 3:
            print("** attribute name missing **")
            return
        elif len(args) < 4:
            print("** value missing **")
            return

        if args[0] not in classes:
            print("** class doesn't exist **")
            return
        for k, v in storage.all().items():
            if args[1] == v.id:
                args[3] = args[3].strip('"')
                try:
                    args[3] = int(args[3])
                except:
                    pass
                setattr(v, args[2], args[3])
                storage.save()
                return
            print("** no instance found **")
Пример #9
0
 def do_count(self, args):
     """Count current number of class instances"""
     count = 0
     if args:
         for inst in storage.all(HBNBCommand.classes[args]):
             count += 1
     print(count)
Пример #10
0
    def do_destroy(self, arg):
        """
        Destroy command to Deletes an instance based on the class name and id
        Usage: destroy <Class_Name> <obj_id>
        """

        args = arg.split()
        container_obj = []
        if len(args) == 0:
            print("** class name missing **")
            return
        try:
            eval(args[0])
        except Exception:
            print("** class doesn't exist **")
            return
        if len(args) == 1:
            print("** instance id missing **")
        else:
            storage.reload()
            container_obj = storage.all()
            key_id = args[0] + "." + args[1]
            if key_id in container_obj:
                del container_obj[key_id]
                storage.save()
            else:
                print("** no instance found **")
Пример #11
0
 def do_all(self, arg):
     """Prints string representations of instances"""
     args = arg.split()
     obj_list = []
     if len(args) == 0:
         obj_dict = storage.all()
     elif args[0] in self.classes:
         obj_dict = storage.all(self.classes[args[0]])
     else:
         print("** class doesn't exist **")
         return False
     for key in obj_dict:
         obj_list.append(str(obj_dict[key]))
     print("[", end="")
     print(", ".join(obj_list), end="")
     print("]")
Пример #12
0
 def do_show(self, arg):
     """
     Show command to Prints the string representation of an instance based
     on
     the class name and id
     Usage: show <Class_Name> <obj_id>
     """
     args = arg.split()
     if len(args) == 0:
         print("** class name missing **")
         return
     try:
         eval(args[0])
     except Exception:
         print("** class doesn't exist **")
         return
     if len(args) == 1:
         print("** instance id missing **")
     else:
         storage.reload()
         container_obj = storage.all()
         key_id = args[0] + "." + args[1]
         if key_id in container_obj:
             value = container_obj[key_id]
             print(value)
         else:
             print("** no instance found **")
Пример #13
0
 def do_count(self, args):
     """Count current number of class instances"""
     count = 0
     for k, v in storage.all(HBNBCommand.classes[args]).items():
         if args == k.split('.')[0]:
             count += 1
     print(count)
Пример #14
0
    def do_update(self, arg):
        """ Updates instance based on cls name/id by attribute, saves to JSON
            Command syntax: update + [cls nme] + [id] + [attr nme] + [attr val]
        """
        if len(arg) == 0:
            print("** class name missing **")
            return
        if len(arg) == 1:
            print("** instance id missing **")
            return
        if len(arg) == 2:
            print("** attribute name missing **")
            return
        if len(arg) == 3:
            print("** value missing **")
            return

        arg = arg.split()
        inst_key = arg[0] + "." + arg[1]

        storage = FileStorage()
        storage.reload()
        all_objs = storage.all()

        try:
            obj_value = all_objs[inst_key]
        except KeyError:
            print("** no instance found**")
            return

        setattr(obj_value, arg[2], arg[3])
        obj_value.save()
Пример #15
0
    def do_destroy(self, args):
        """Deletes the instance indicated and removes it from
        the JSON file."""
        args = shlex.split(args)

        if len(args) == 0:
            print("** class name missing **")
            return
        elif args[0] not in model_names:
            print("** class doesn't exist **")
            return
        elif len(args) != 2:
            print("** instance id missing **")
            return

        cls, idx = args[0], args[1]
        storage = FileStorage()
        storage.reload()
        obj_dict = storage.all()
        key = cls + '.' + idx

        try:
            del obj_dict[key]
        except KeyError:
            print("** no instance found **")
        storage.save()
Пример #16
0
    def do_all(self, input_line, flag=True):
        '''Prints all string representation of
        all instances based or not on the class name.'''

        splited_input = input_line.split()
        splited_input_len = len(splited_input)

        if splited_input_len > 0 and splited_input[0] not in allowed_classes:
            print("** class doesn't exist **")
            return

        else:
            instances = storage.all()
            instances_list = []

            for single_instance in instances.keys():
                if splited_input_len == 0:
                    instances_list.append(instances[single_instance].__str__())

                elif splited_input_len > 0:
                    if single_instance.split('.')[0] == splited_input[0]:
                        instances_list.append(
                            instances[single_instance].__str__())

            if flag is True:
                print(instances_list)

            else:
                return (len(instances_list))
Пример #17
0
    def do_show(self, args):
        """ Method to show an individual object """
        new = args.partition(" ")
        c_name = new[0]
        c_id = new[2]

        # guard against trailing args
        if c_id and ' ' in c_id:
            c_id = c_id.partition(' ')[0]

        if not c_name:
            print("** class name missing **")
            return

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

        if not c_id:
            print("** instance id missing **")
            return

        key = c_name + "." + c_id
        try:
            print(storage.all()[key])
        except KeyError:
            print("** no instance found **")
Пример #18
0
    def do_show(self, input_line):
        '''Prints the string representation of
        an instance based on the class name and id'''

        splited_input = input_line.split()
        splited_input_len = len(splited_input)

        if splited_input_len < 1:
            print("** class name missing **")
            return

        if splited_input[0] not in allowed_classes:
            print("** class doesn't exist **")
            return

        if splited_input_len < 2:
            print("** instance id missing **")
            return

        instances = storage.all()
        obj_reference = splited_input[0] + "." + splited_input[1]

        if obj_reference in instances.keys():
            print(instances[obj_reference])
        else:
            print("** no instance found **")
Пример #19
0
 def do_update(self, arg):
     """Updates an instance based on the class name and id by adding
     or updating attribute (save the change into the JSON file)
     """
     objs = storage.all()
     args = arg.split()
     if len(args) == 0:
         print("** class name missing **")
     elif args[0] not in HBNBCommand.classes:
         print("** class doesn't exist **")
     elif len(args) == 1:
         print("** instance id missing **")
     elif "{}.{}".format(args[0], args[1]) not in objs.keys():
         print("** no instance found **")
     elif len(args) == 2:
         print("** attribute name missing **")
     elif len(args) == 3:
         try:
             type(eval(args[2])) != dict
         except NameError:
             print("** value missing **")
     elif len(args) == 4:
         obj = objs["{}.{}".format(args[0], args[1])]
         obj.__dict__.update({args[2]: args[3]})
         obj.save()
Пример #20
0
    def do_destroy(self, input_line):
        '''Deletes an instance based on the class
        name and id (save the change into the JSON file'''

        splited_input = input_line.split()
        splited_input_len = len(splited_input)
        if splited_input_len < 1:
            print("** class name missing **")
            return

        if splited_input[0] not in allowed_classes:
            print("** class doesn't exist **")
            return

        if splited_input_len < 2:
            print("** instance id missing **")
            return

        instances = storage.all()
        obj_reference = splited_input[0] + "." + splited_input[1]

        if obj_reference in instances.keys():
            del instances[obj_reference]
            storage.save()
        else:
            print("** no instance found **")
Пример #21
0
 def do_show(self, line):
     """ show the object base the id
     use 'show [NAME_OBJECT] [ID]'
     """
     # Create argv for line
     argv = line.split()
     argc = len(argv)
     # Create a flag
     id_ins = False
     # Verify if argc is 0
     if argc == 0:
         print("** class name missing **")
         return
     # Verify if the NAME_OBJECT is not exist in base
     if argv[0] not in base:
         # Print error
         print("** class doesn't exist **")
         return
     # Verify if have BaseName but not id
     if argc == 1:
         # Print error
         print("** instance id missing **")
         return
     # Get all instances
     instances = storage.all()
     # Construct the key ref for verify the instance
     key_ref = argv[0] + "." + argv[1]
     # Verify if key_ref exist in instances.keys()
     if key_ref in instances.keys():
         print(instances[key_ref])
     else:
         print("** no instance found **")
Пример #22
0
 def do_update(self, arg):
     obj_dict = storage.all()
     args = arg.split(" ")
     if arg is '':
         print("** class name missing **")
     elif args[0] not in HBNBCommand.classes:
         print("** class doesn't exist **")
     elif len(args) < 2:
         print("** instance id missing **")
     else:
         for key, value in obj_dict.items():
             skey = key.split(".")
         if skey[0] != args[0]:
             print("** no instance found **")
         else:
             if len(args) < 3:
                 print("** attribute name missing **")
             elif len(args) < 4:
                 print("** value missing **")
             else:
                 for key, value in obj_dict.items():
                     skey = key.split(".")
                     if skey[1] == args[1]:
                         val = args[3]
                         updater = {args[2]: val.replace('"', '')}
                         (obj_dict[key].__dict__).update(updater)
                 storage.save()
Пример #23
0
    def do_show(self, line):
        """Prints string representation of an instance"""

        args = split(line)
        if len(args) == 0:
            print("** class name missing **")
            return
        if len(args) == 1:
            print("** instance id missing **")
            return
        storage = FileStorage()
        storage.reload()
        objDict = storage.all()

        try:
            eval(args[0])

        except NameError:
            print("** class doesn't exist **")
            return
        key = args[0] + "." + args[1]

        try:
            value = objDict[key]
            print(value)

        except KeyError:
            print("** no instance found **")
Пример #24
0
    def default(self, line):
        if "." not in line:
            return cmd.Cmd.default(self, line)
        syntax = line.split(".")
        _class = syntax[0]
        method = syntax[1]
        obj_dict = storage.all()

        if _class in HBNBCommand.classes:
            if method[0:5] == 'all()':
                HBNBCommand.do_all(self, _class)
            if method[0:8] == 'count()':
                HBNBCommand.do_count(self, _class)
            arg_split = method.split('"')
            method_id = arg_split[0]
            if method_id[0:5] == 'show(':
                class_id = arg_split[1]
                arg = _class + " " + class_id
                HBNBCommand.do_show(self, arg)
            if method_id[0:8] == 'destroy(':
                class_id = arg_split[1]
                arg = _class + " " + class_id
                HBNBCommand.do_destroy(self, arg)
            if method_id[0:7] == 'update(':
                arg_split2 = method.split(",")
                class_id = arg_split2[0].split("(")[1].replace('"', "")
                print(class_id)
                att_name = arg_split2[1].replace('"', "")
                print(att_name)
                att_val = arg_split2[2].replace(")", "")
                print(att_val)
                arg = _class + " " + class_id + " " + att_name[1:] + att_val
                print(arg)
                HBNBCommand.do_update(self, arg)
Пример #25
0
 def do_count(self, args):
     """Count current number of class instances"""
     count = 0
     for k in storage.all():
         if args == k.split('.')[0]:
             count += 1
     print(count)
Пример #26
0
 def do_update(self, args):
     """ Updates an instance based on the class name and id by adding
     or updating attribute (save the change into the JSON file)"""
     args = args.split()
     size = len(args)
     objs = storage.all()
     if not args:
         print("** class name missing **")
     elif not args[0] in classes.keys():
         print("** class doesn't exist **")
     elif size < 2:
         print("** instance id missing **")
     elif not ".".join([args[0], args[1]]) in objs.keys():
         print("** no instance found **")
     elif size < 3:
         print("** attribute name missing **")
     elif size < 4:
         print("** value missing **")
     else:
         try:
             obj = objs[".".join([args[0], args[1]])]
             setattr(obj, args[2], args[3])
             storage.save()
         except Exception as e:
             print(e)
             print("** Update fail **")
Пример #27
0
 def do_all(self, args):
     """Shows all objects, or all objects of a class"""
     comm = args.split()
     arg_list = []
     if args and comm[0] not in HBNBCommand.classes.keys():
         print("** class doesn't exist **")
     elif not args:
         obj = storage.all()
         for key in obj:
             arg_list.append(str(obj[key]))
             print(arg_list)
     else:
         obj = storage.all(eval(comm[0]))
         for key in obj:
             arg_list.append(str(obj[key]))
             print(arg_list)
Пример #28
0
    def do_show(self, args):
        """Prints the class name and id."""
        args = shlex.split(args)
        if len(args) == 0:
            print("** class name missing **")
            return
        elif args[0] not in model_names:
            print("** class doesn't exist **")
            return
        elif len(args) != 2:
            print("** instance id missing **")
            return
        cls, idx = args[0], args[1]
        # try:
        #     eval(args[0])
        # except NameError:
        #     print("** class doesn't exist **")
        #     return

        storage = FileStorage()
        storage.reload()
        obj_dict = storage.all()
        key = cls + '.' + idx

        try:
            obj = obj_dict[key]
            print(obj)
        except KeyError:
            print("** no instance found **")
Пример #29
0
    def do_all(self, args):
        """ Shows all objects, or all objects of a class"""
        print_list = []

        if args:
            args = args.split(' ')[0]  # remove possible trailing args
            if args not in HBNBCommand.classes:
                print("** class doesn't exist **")
                return
            for k, v in storage.all(HBNBCommand.classes[args]).items():
                if k.split('.')[0] == args:
                    print_list.append(str(v))
        else:
            for k, v in storage.all().items():
                print_list.append(str(v))
        print(print_list)
Пример #30
0
 def do_destroy(self, args):
     """ deletes instance base on class name and id """
     args = shlex.split(args)
     if len(args) == 0:
         print("** class name missing **")
         return
     elif len(args) == 1:
         print("** instance id missing **")
         return
     classN = args[0]
     classI = args[1]
     storage = FileStorage()
     storage.reload()
     object_dict = storage.all()
     try:
         eval(classN)
     except NameError:
         print("** class doesn't exist **")
         return
     keys = classN + "." + classI
     try:
         del object_dict[keys]
     except KeyError:
         print("** no instance found **")
     storage.save()