Exemplo n.º 1
0
 def do_create(self, line):
     """Creates a new instance.\n"""
     if line == "" or line is None:
         print("** class name missing **")
     elif line not in storage.classes():
         print("** class doesn't exist **")
     else:
         inst = storage.classes()[line]()
         inst.save()
         print(inst.id)
Exemplo n.º 2
0
    def do_create(self, line):
        """Creates a new instance, \
saves it (to the JSON file) and prints the id\n"""
        if line in storage.classes():
            new_obj = storage.classes()[line]()
            storage.save()
            print(new_obj.id)
        elif line == "":
            print("** class name missing **")
        else:
            print("** class doesn't exist **")
Exemplo n.º 3
0
 def do_create(self, line):
     """Creates a new instance of BaseModel,
     saves it (to the JSON file) and prints the id
     """
     if line == "" or line is None:
         print("** class name missing **")
     elif line not in storage.classes():
         print("** class doesn't exist **")
     else:
         instance = storage.classes()[line]()
         instance.save()
         print(instance.id)
Exemplo n.º 4
0
    def do_create(self, command):
        """
        Creates a new instance of BaseModel.
        """
        if command == "" or command is None:
            print("** class name missing **")
            return

        tokens = command.split(" ")
        if tokens[0] not in storage.classes():
            print("** class doesn't exist **")
        else:
            new = storage.classes()[tokens[0]]()
            new.save()
            print(new.id)
Exemplo n.º 5
0
    def do_update(self, line):
        """Update an instance based on class name and id.\n"""
        if line == "" or line is None:
            print("** class name missing **")
            return
        terms = shlex.split(line, posix=False)
        if terms[0] not in storage.classes():
            print("** class doesn't exist **")
            return
        elif len(terms) < 2:
            print("** instance id missing **")
            return
        #ok so we have a class and an instance id
        # does key exist
        key = "{}.{}".format(terms[0], terms[1])
        if key not in storage.all():  #all().keys()?
            print("** no instance found **")
            return

        if len(terms) < 3:
            print("** attribute name missing **")
            return
        elif len(terms) < 4:
            print("** value missing **")
            return
        terms[3] = terms[3].strip("\"")
        storage.all()[key].__dict__[terms[2]] = terms[3]
        storage.save()
Exemplo n.º 6
0
    def do_destroy(self, command):
        """
        Deletes an instance based on the class name
        and id (save the change into the JSON file)
        """
        if not command:
            print("** class name missing **")
            return
        tokens = command.split(" ")
        objects = storage.all()

        if tokens[0] in storage.classes():
            if len(tokens) < 2:
                print("** instance id missing **")
                return
            name = tokens[0] + "." + tokens[1]
            if name not in objects:
                print("** no instance found **")
            else:
                obj_de = objects[name]
                """
                obj_de stands for object to destroy
                """
                if obj_de:
                    objs = storage.all()
                    del objs["{}.{}".format(type(obj_de).__name__, obj_de.id)]
                    storage.save()
        else:
            print("** class doesn't exist **")
Exemplo n.º 7
0
    def default(self, line):
        """Handle class.cmd(args) commands """
        if not re.search("\.(\w+)\(", line):
            return
        cl_name = line.split(".")[0]
        cmd = line.split(".")[1].split("(")[0]
        term = line.split("(")[1][:-1]

        if cl_name is "":
            print("** class name missing **")
            return
        elif cl_name not in storage.classes():
            print("** class doesn't exist **")
            return

        if cmd == "all":
            self.do_all(cl_name)

        elif cmd == "count":
            count = sum(1 for k, v in storage.all().items()
                        if v.to_dict()["__class__"] == cl_name)
            print(count)

        elif cmd == "show":
            self.do_show(cl_name + " " + term.strip("\""))

        elif cmd == "destroy":
            self.do_destroy(cl_name + " " + term.strip("\""))

        elif cmd == "update":
            # if starts with 'id, {}', then split into id and dict
            if re.match('"[^"]+", {.+}', term):
                term = term.replace("\'", "\"")
                term_dict = json.loads(term.split(", ", 1)[1])
                term_id = cl_name + "." + term.split(", ")[0].strip("\"")
                if term_id not in storage.all().keys():
                    print("** no instance found **")
                    return
                for k, v in term_dict.items():
                    setattr(storage.all()[term_id], k, v)
            # else update at id the attribute with new_value
            else:
                terms = term.split(", ")
                if terms == ['']:
                    print("** instance id missing **")
                    return
                key = "{}.{}".format(cl_name, terms[0].strip("\""))
                if key not in storage.all().keys():
                    print("** no instance found **")
                    return
                if len(terms) < 2:
                    print("** attribute name missing **")
                    return
                if len(terms) < 3:
                    print("** value missing **")
                    return
                self.do_update(cl_name + " " + terms[0].strip("\"") + " " +
                               terms[1].strip("\"") + " " + terms[2])
        else:
            super().default(line)
Exemplo n.º 8
0
 def do_update(self, command):
     """
     Update an instance based on the class name and
     id by adding or updating attribute
     (save the change into the JSON file).
     """
     if not command:
         print("** class name missing **")
         return
     tokens = command.split(" ")
     objects = storage.all()
     if tokens[0] in storage.classes():
         if len(tokens) < 2:
             print("** instance id missing **")
             return
         name = tokens[0] + "." + tokens[1]
         if name not in objects:
             print("** no instance found **")
         else:
             obj_update = objects[name]
             denied_access = ["id", "created_at", "updated_at"]
             if obj_update:
                 arguments = command.split(" ")
                 if len(arguments) < 3:
                     print("** attribute name missing **")
                 elif len(arguments) < 4:
                     print("** value missing **")
                 elif arguments[2] not in denied_access:
                     obj_update.__dict__[arguments[2]] = arguments[3]
                     obj_update.updated_at = datetime.now()
                     storage.save()
     else:
         print("** class doesn't exist **")
Exemplo n.º 9
0
    def do_update(self, line):
        """ Prints all string representation
            of all instances based or not on the class name.
        """
        if not line:
            print("** class name missing **")
            return

        w = shlex.split(line)
        if w[0] not in storage.classes():
            print("** class doesn't exist **")
        elif len(w) == 1:
            print("** instance id missing **")
        else:
            obj = storage.all()
            for key, value in obj.items():
                ob_name = value.__class__.__name__
                ob_id = value.id
                if ob_name == w[0] and ob_id == w[1].strip('"'):
                    if len(w) == 2:
                        print("** attribute name missing **")
                    elif len(w) == 3:
                        print("** value missing **")
                    else:
                        setattr(value, w[2], w[3].strip('"'))
                        storage.save()
                    return
            print("** no instance found **")
Exemplo n.º 10
0
 def tool_test_new(self, classname):
     """new() testing helper"""
     self.resetStorage()
     cls = storage.classes()[classname]
     rat = cls()
     storage.new(rat)
     key = "{}.{}".format(type(rat).__name__, rat.id)
     self.assertTrue(key in FileStorage._FileStorage__objects)
     self.assertEqual(FileStorage._FileStorage__objects[key], rat)
Exemplo n.º 11
0
    def tool_test_all(self, classname):
        """test all() method"""
        self.resetStorage()
        self.assertEqual(storage.all(), {})

        rat = storage.classes()[classname]()
        storage.new(rat)
        key = "{}.{}".format(type(rat).__name__, rat.id)
        self.assertTrue(key in storage.all())
        self.assertEqual(storage.all()[key], rat)
Exemplo n.º 12
0
 def do_count(self, arg):
     """Counts"""
     args = arg.split(' ')
     if self.check_class(args[0]):
         if args[0] not in storage.classes():
             print("** class doesn't exist **")
     else:
         for k in storage.all():
             print(k)
             if k.startswith(args[0] + '.'):
                 print(len(k))
Exemplo n.º 13
0
 def test_classes(self):
     """ test if 'classes' returns a dict with the classes """
     dictionary = {
         'BaseModel': BaseModel,
         'User': User,
         'State': State,
         'City': City,
         'Amenity': Amenity,
         'Place': Place,
         'Review': Review
     }
     self.assertEqual(storage.classes(), dictionary)
Exemplo n.º 14
0
 def tool_test_reload(self, classname):
     """ a tool to help test reloading"""
     self.resetStorage()
     storage.reload()
     self.assertEqual(FileStorage._FileStorage__objects, {})
     cls = storage.classes()[classname]
     obj = cls()
     storage.new(obj)
     key = "{}.{}".format(type(obj).__name__, obj.id)
     storage.save()
     storage.reload()
     self.assertEqual(obj.to_dict(), storage.all()[key].to_dict())
Exemplo n.º 15
0
    def tool_test_all_multiple(self, classname):
        """to test all() /many objects"""
        self.resetStorage()
        self.assertEqual(storage.all(), {})

        cls = storage.classes()[classname]
        obj = [cls() for i in range(1000)]
        [storage.new(thing) for thing in obj]
        self.assertEqual(len(obj), len(storage.all()))
        for thing in obj:
            key = "{}.{}".format(type(thing).__name__, thing.id)
            self.assertTrue(key in storage.all())
            self.assertEqual(storage.all()[key], thing)
Exemplo n.º 16
0
 def do_count(self, line):
     """Counts the instances of a class.
     """
     words = line.split(' ')
     if not words[0]:
         print("** class name missing **")
     elif words[0] not in storage.classes():
         print("** class doesn't exist **")
     else:
         matches = [
             k for k in storage.all() if k.startswith(
                 words[0] + '.')]
         print(len(matches))
Exemplo n.º 17
0
 def do_all(self, line):
     """Prints all string representation of all instances.
     """
     if line != "":
         words = line.split(' ')
         if words[0] not in storage.classes():
             print("** class doesn't exist **")
         else:
             l = [str(obj) for key, obj in storage.all().items()
                  if type(obj).__name__ == words[0]]
             print(l)
     else:
         l = [str(obj) for key, obj in storage.all().items()]
         print(l)
Exemplo n.º 18
0
 def do_count(self, command):
     """
     Counts number of instances of a specific class
     """
     objects = storage.all()
     count = 0
     tokens = command.split('.')
     if tokens[0] in storage.classes():
         for name in objects:
             if name[0:len(tokens[0])] == tokens[0]:
                 count += 1
         print(count)
     else:
         pass
Exemplo n.º 19
0
 def tool_test_save(self, classname):
     """helper func for save tests"""
     self.resetStorage()
     cls = storage.classes()[classname]
     obj = cls()
     storage.new(obj)
     key = "{}.{}".format(type(obj).__name__, obj.id)
     storage.save()
     self.assertTrue(os.path.isfile(FileStorage._FileStorage__file_path))
     dick = {key: obj.to_dict()}
     with open(FileStorage._FileStorage__file_path,
               "r", encoding="utf-8") as f:
         self.assertEqual(len(f.read()), len(json.dumps(dick)))
         f.seek(0)
         self.assertEqual(json.load(f), dick)
Exemplo n.º 20
0
    def do_all(self, line):
        """Prints all string representation of all \
instances based or not on the class name\n"""
        if not line or line == "":
            l = [str(value) for key, value in storage.all().items()]
        else:
            tokens = line.split(" ")
            if tokens[0] not in storage.classes():
                print("** class doesn't exist **")
                return
            l = [
                str(value) for key, value in storage.all().items()
                if type(value).__name__ == tokens[0]
            ]
        print(l)
Exemplo n.º 21
0
 def do_all(self, line):
     """Displays all instances, display all of a class of instances.\n"""
     if line is not "":
         terms = line.split(' ')
         if terms[0] not in storage.classes():
             print("** class doesn't exist **")
         else:
             obj_list = [
                 str(obj) for key, obj in storage.all().items()
                 if type(obj).__name__ == terms[0]
             ]
             print(obj_list)
     else:
         obj_list = [str(obj) for key, obj in storage.all().items()]
         print(obj_list)
Exemplo n.º 22
0
 def do_show(self, line):
     """Prints an instance by id.\n"""
     if line is "" or line is None:
         print("** class name missing **")
     else:
         terms = line.split(' ')
         if terms[0] not in storage.classes():
             print("** class doesn't exist **")
         elif len(terms) < 2 or terms[1] is "":
             print("** instance id missing **")
         else:
             key = "{}.{}".format(terms[0], terms[1])
             if key not in storage.all():
                 print("** no instance found **")
             else:
                 print(storage.all()[key])
Exemplo n.º 23
0
    def do_update(self, line):
        """Updates an instance based on the class name and id \
by adding or updating attribute (save the change into the JSON file).
Usage: update <class name> <id> <attribute name> "<attribute value>"\n"""
        if line == "":
            print("** class name missing **")
            return
        tokens = line.split(" ")
        if tokens[0] not in storage.classes():
            print("** class doesn't exist **")
            return
        if len(tokens) < 2:
            print("** instance id missing **")
            return
        id_obj = str(tokens[0] + "." + tokens[1])
        if id_obj not in storage.all():
            print("** no instance found **")
            return
        if len(tokens) < 3:
            print("** attribute name missing **")
            return
        if '{' in tokens[2]:
            dic = json.loads(" ".join(elem for elem in tokens[2:]))
            for key, value in dic.items():
                setattr(storage.all()[tokens[0] + "." + tokens[1]], key, value)
                storage.all()[tokens[0] + "." + tokens[1]].save()
            return
        if len(tokens) < 4:
            print("** value missing **")
            return
        if tokens[3][0] == '"':
            value = " ".join(token for token in tokens[3:])
            value = value.split('"')[1]
        else:
            value = tokens[3]
        if '.' in value:
            try:
                value = float(value)
            except ValueError:
                pass
        else:
            try:
                value = int(value)
            except ValueError:
                pass
        setattr(storage.all()[tokens[0] + "." + tokens[1]], tokens[2], value)
        storage.all()[tokens[0] + "." + tokens[1]].save()
Exemplo n.º 24
0
 def do_show(self, line):
     """Prints the string representation of an instance.
     """
     if line == "" or line is None:
         print("** class name missing **")
     else:
         words = line.split(' ')
         if words[0] not in storage.classes():
             print("** class doesn't exist **")
         elif len(words) < 2:
             print("** instance id missing **")
         else:
             key = "{}.{}".format(words[0], words[1])
             if key not in storage.all():
                 print("** no instance found **")
             else:
                 print(storage.all()[key])
Exemplo n.º 25
0
 def do_destroy(self, line):
     """Deletes an instance based on the class name and id.\n"""
     if line is "" or line is None:
         print("** class name missing **")
     else:
         terms = line.split(' ')
         if terms[0] not in storage.classes():
             print("** class doesn't exist **")
         elif len(terms) < 2 or terms[1] is "":
             print("** instance id missing **")
         else:
             key = "{}.{}".format(terms[0], terms[1])
             if key not in storage.all():
                 print("** no instance found **")
             else:
                 del storage.all()[key]
                 storage.save()
Exemplo n.º 26
0
    def do_update(self, line):
        """Updates an instance by adding or updating attribute.
        """
        if line == "" or line is None:
            print("** class name missing **")
            return

        rex = r'^(\S+)(?:\s(\S+)(?:\s(\S+)(?:\s((?:"[^"]*")|(?:(\S)+)))?)?)?'
        match = re.search(rex, line)
        classname = match.group(1)
        uid = match.group(2)
        attribute = match.group(3)
        value = match.group(4)
        if not match:
            print("** class name missing **")
        elif classname not in storage.classes():
            print("** class doesn't exist **")
        elif uid is None:
            print("** instance id missing **")
        else:
            key = "{}.{}".format(classname, uid)
            if key not in storage.all():
                print("** no instance found **")
            elif not attribute:
                print("** attribute name missing **")
            elif not value:
                print("** value missing **")
            else:
                cast = None
                if not re.search('^".*"$', value):
                    if '.' in value:
                        cast = float
                    else:
                        cast = int
                else:
                    value = value.replace('"', '')
                attributes = storage.attributes()[classname]
                if attribute in attributes:
                    value = attributes[attribute](value)
                elif cast:
                    try:
                        value = cast(value)
                    except ValueError:
                        pass  # fine, stay a string then
                setattr(storage.all()[key], attribute, value)
                storage.all()[key].save()
Exemplo n.º 27
0
 def do_all(self, line):
     """ Prints all string representation
         of all instances based or not on the class name.
     """
     lis = []
     if line != "":
         w = line.split(' ')
         if w[0] not in storage.classes():
             print("** class doesn't exist **")
         else:
             for k, obj in storage.all().items():
                 if type(obj).__name__ == w[0]:
                     lis.append(str(obj))
             print(lis)
     else:
         for k, obj in storage.all().items():
             lis.append(str(obj))
         print(lis)
Exemplo n.º 28
0
    def do_show(self, line):
        """Prints the string representation of an \
instance based on the class name and id\n"""
        if line == "":
            print("** class name missing **")
            return
        tokens = line.split(" ")
        if tokens[0] not in storage.classes():
            print("** class doesn't exist **")
            return
        if len(tokens) < 2:
            print("** instance id missing **")
            return
        id_obj = str(tokens[0] + "." + tokens[1])
        if id_obj not in storage.all():
            print("** no instance found **")
        else:
            print(storage.all()[id_obj])
Exemplo n.º 29
0
 def do_destroy(self, line):
     """Deletes an instance based on the class name and id\n"""
     if line == "":
         print("** class name missing **")
         return
     tokens = line.split(" ")
     if tokens[0] not in storage.classes():
         print("** class doesn't exist **")
         return
     if len(tokens) < 2:
         print("** instance id missing **")
         return
     id_obj = str(tokens[0] + "." + tokens[1])
     if id_obj not in storage.all():
         print("** no instance found **")
     else:
         del storage.all()[id_obj]
         storage.save()
Exemplo n.º 30
0
 def do_all(self, command):
     """
     Prints all string representation of all
     instances based or not on the class name.
     """
     objects = storage.all()
     instances = []
     if not command:
         for name in objects:
             instances.append(objects[name])
         print(instances)
         return
     tokens = command.split(" ")
     if tokens[0] in storage.classes():
         for name in objects:
             if name[0:len(tokens[0])] == tokens[0]:
                 instances.append(objects[name])
         print(instances)
     else:
         print("** class doesn't exist **")