def do_create(self, args): """ Create an object of any class""" command = args.split() obj_dict = {} if not args: print("** class name missing **") return elif command[0] not in HBNBCommand.classes: print("** class doesn't exist **") return if len(command) == 1: if command[0] in HBNBCommand.classes: new_instance = HBNBCommand.classes[command[0]]() storage.new(new_instance) storage.save() print(new_instance.id) return else: print("** class doesn't exist **") return else: attributes = command.copy() del attributes[0] try: for att in attributes: p1, p2 = att.split('=') obj_dict[p1] = p2.replace("\"", "").replace("_", " ") new_instance = HBNBCommand.classes[command[0]](**obj_dict) storage.new(new_instance) print(new_instance.id) storage.save() except(AttributeError): pass
def do_create(self, args): """ Create an object of any class""" if not args: print("** class name missing **") return list_arguments = args.split() if list_arguments[0] not in HBNBCommand.classes: print("** class doesn't exist **") return arg_dict = {} if len(list_arguments) > 1: for index, argu in enumerate(list_arguments): if index > 0: x = re.search("^[a-zA-Z][\w]*=[\"]?(.*)[\"]?", argu) if not x: return else: key = argu.split("=")[0] value = argu.split("=")[1] if re.search("^[\"](.*[\"])?$", value): arg_dict[key] = value[1:-1].replace("_", " ") else: if "." in value: arg_dict[key] = float(value) else: try: arg_dict[key] = int(value) except ValueError: return new_instance = HBNBCommand.classes[list_arguments[0]]() new_instance.__dict__.update(arg_dict) storage.new(new_instance) storage.save() print(new_instance.id)
def do_create(self, args): """ Create an object of any class""" n_args = args.split(" ") if not args: print("** class name missing **") return elif n_args[0] not in HBNBCommand.classes: print("** class doesn't exist **") return new_instance = HBNBCommand.classes[n_args[0]]() # update added here # storage.new(new_instance) for i in range(1, len(n_args)): if '=' in n_args[i]: key_value = n_args[i].split("=") if key_value[0] == 'id': key_value[1] = str(key_value[1]) new_instance.__dict__[key_value[0]] = key_value[1] if key_value[1][0] == '"': if '_' in key_value[1]: key_value[1] = key_value[1].replace("_", " ") new_instance.__dict__[key_value[0]] = key_value[1][1:-1] elif '.' in key_value[1]: new_instance.__dict__[key_value[0]] = float(key_value[1]) elif int(key_value[1]): new_instance.__dict__[key_value[0]] = int(key_value[1]) print(new_instance.id) storage.new(new_instance) storage.save()
def do_create(self, args): """ Create an object of any class""" if not args: print("** class name missing **") return list_arg = args.split(" ") if list_arg[0] not in HBNBCommand.classes: print("** class doesn't exist **") return new_instance = HBNBCommand.classes[list_arg[0]]() if len(list_arg) > 1: for i in list_arg[1:]: key = i.split('=')[0] val = i.split('=')[1] if val[0] is '\"' or val[0] is "'": val = val.replace('_', ' ') val = val[1:-1] elif "." in val: val = float(val) else: val = int(val) setattr(new_instance, key, val) storage.new(new_instance) storage.save() print(new_instance.id)
def do_create(self, args): """ Create an object of any class""" if not args: print("** class name missing **") return else: args = args.split(' ') if args[0] not in HBNBCommand.classes: print("** class doesn't exist **") return new_instance = HBNBCommand.classes[args[0]]() for element in args[1:]: atr = element.split('=') if atr[1][0] == '"': atr[1] = atr[1][1:-1].replace('"', '\\"') atr[1] = atr[1].replace("_", " ") elif atr[1].isdecimal is True: atr[1] = Int(atr[1]) else: try: float(atr[1]) except ValueError: pass setattr(new_instance, atr[0], atr[1]) print(new_instance.id) if getenv('HBNB_TYPE_STORAGE') == 'db': storage.new(new_instance) storage.save() else: new_instance.save()
def do_create(self, arg): """ Create an object of any class""" if not arg: print("** class name missing **") return args = arg.split() if args[0] not in HBNBCommand.classes: print("** class doesn't exist **") return new_instance = HBNBCommand.classes[args[0]]() for x in args: if "=" not in x: continue temp = x.split("=") key = temp[0] raw = temp[1] value = None if "\"" in raw: value = raw[1:-1] value = value.replace("_", " ") elif "." in raw: value = float(raw) else: value = int(raw) setattr(new_instance, key, value) storage.new(new_instance) print(new_instance.id) storage.save()
def do_create(self, line): """ Create an object of any class""" try: if not line: raise SyntaxError() l = line.split(" ") kwargs = {} for i in range(1, len(l)): k, v = tuple(l[i].split("=")) if v[0] == '"': v = v.strip('"').replace("_", " ") else: try: v = eval(v) except (SyntaxError, NameError): continue kwargs[k] = v if kwargs == {}: obj = eval(l[0])() else: obj = eval(l[0])(**kwargs) storage.new(obj) print(obj.id) obj.save() except SyntaxError: print("** class name missing **") except NameError: print("** class doesn't exist **")
def test_new(self): """Test new method """ for key, value in TestFileStorage.models.items(): instance = value() storage.new(instance) key_obj = "{}.{}".format(type(instance).__name__, instance.id) self.assertTrue(key_obj in storage.all()) self.assertTrue(storage.all()[key_obj], instance)
def test_save(self): """Test for save method """ for key, value in TestFileStorage.models.items(): instance = value() storage.new(instance) storage.save() with open("file.json") as file: self.assertIsInstance(json.load(file), dict)
def test_reload(self): """Test for reload method """ for key, value in TestFileStorage.models.items(): instance = value() tmp_id = instance.id storage.new(instance) storage.reload() key_obj = "{}.{}".format(key, tmp_id) tmp_dic = storage.all() self.assertTrue(key_obj in tmp_dic)
def do_create(self, args): """ Create an object of any class""" args = args.split() if len(args) == 0: print("** class name missing **") return elif args[0] not in HBNBCommand.classes: print("** class doesn't exist **") return new_instance = HBNBCommand.classes[args[0]]() # If there are more arguments being passed (<name>="<value>") if len(args) > 1: # For every argument after the first (which was class name) for string in args[1:]: # Skip arg if it doesn't match name=value if '=' not in string or string[0] == '=' or string[-1] == '=': continue # Attribute name is everything before '=' attr_name = string[:string.find('=')] # If attribute name does not belong to this class, skip if attr_name not in HBNBCommand.class_attrs[args[0]]: continue # Attribute value is everything after '=' attr_value = string[string.find('=') + 1:] # Remove double quotes if they exist and label type as string # If there isn't a complete pair of quotes, skip # If no quotes are found, label as float or int accordingly if attr_value[0] == '"' and attr_value[-1] == '"': attr_value = attr_value[1:-1] attr_type = str elif attr_value[0] == '"' or attr_value[-1] == '"': continue else: if '.' in attr_value: attr_type = float else: attr_type = int # Replace any underscores with spaces attr_value = attr_value.replace("_", " ") # Set attribute setattr(new_instance, attr_name, attr_type(attr_value)) storage.new(new_instance) print(new_instance.id) storage.save()
def __init__(self, *args, **kwargs): """Task 3 - Initialization of instances""" if kwargs: for key, value in kwargs.items(): if key != "__class__": if key == "created_at" or key == "updated_at": setattr( self, key, datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")) else: setattr(self, key, value) else: self.id = str(uuid.uuid4()) self.created_at = datetime.now() self.updated_at = datetime.now() storage.new(self)
def __init__(self, *args, **k): """Initializer function (also known as constructor) Will make an object with specific values if given kwargs, otherwise, standard """ if k: fmt = "%Y-%m-%dT%H:%M:%S.%f" if "created_at" in k and type(k["created_at"]) is str: k["created_at"] = datetime.strptime(k["created_at"], fmt) if "updated_at" in k and type(k["updated_at"]) is str: k["updated_at"] = datetime.strptime(k["updated_at"], fmt) k.pop("__class__", "pizza") self.__dict__.update(k) else: self.id = str(uuid.uuid4()) self.created_at = datetime.now() self.updated_at = datetime.now() storage.new(self)
def __init__(self, *args, **kwargs): """ initializes instance attributes """ time = '%Y-%m-%d %H:%M:%S.%f' dict_found = 0 for item in args: if type(item) is dict: dict_found = 1 self.__dict__ = item self.created_at = datetime.strptime(item['created_at'], time) if hasattr(item, 'updated_at'): self.updated_at = datetime.strptime (item['updated_at'], time) if dict_found == 0: self.created_at = datetime.now() self.id = str(uuid.uuid4()) from models.__init__ import storage storage.new(self)
def __init__(self, *args, **kwargs): """Instantion method""" if len(kwargs) != 0: """Create instance""" for key, val in kwargs.items(): if key == '__class__': setattr(self, key, type(self)) elif key == 'created_at' or key == 'updated_at': """Formats datetime""" setattr(self, key, d.strptime(val, "%Y-%m-%dT%H:%M:%S.%f")) else: setattr(self, key, val) else: """No dict create new instance""" self.id = str(uuid.uuid4()) self.created_at = d.now() self.updated_at = self.created_at from models.__init__ import storage storage.new(self)
def do_create(self, args): """ Create an object of any class""" argument = args.split() # partimos el argumento if not args: print("** class name missing **") return elif argument[0] not in HBNBCommand.classes: print("** class doesn't exist **") return param = {} for item in argument[1:]: if "=" in item: # partir el array EX "name='Arizona'" split_2 = item.split("=") key = split_2[0] value = split_2[1] else: continue if value != value.strip('"'): # starts with double quote value = value.strip('"') value = value.replace("_", " ") param[key] = value # asignar key y value al dictionary elif "." in value: param[key] = float(value) else: try: param[key] = int(value) except: pass new_instance = HBNBCommand.classes[argument[0]](**param) print(new_instance.id) storage.new(new_instance) storage.save()
def do_create(self, command: str): """ Create an object of any class""" try: className = command.split()[0] if className not in HBNBCommand.classes: print("** class doesn't exist **") return else: new_instance = HBNBCommand.classes[className]() except Exception: print("** class name missing **") return # create Place latitude=20.6 max_guest=6 name=state1 try: args = command.split()[1:] new_obj = new_instance.__dict__ # list of instance attr obj_arg = new_instance.__class__.__dict__ for arg in args: key = arg.split('=')[0] # print('obj_arg',obj_arg) if key not in obj_arg: # if key is not in inst attr continue # ignore it val = arg.split('=')[1] val = self.treat_string(val) if key in HBNBCommand.types: try: val = HBNBCommand.types[key](val) # if we cant cast it except Exception: continue # escape it # if the val in instance attr && val can be casted we add them new_obj[key] = val storage.new(new_instance) print(new_instance.id) storage.save() return except Exception: raise Exception finally: pass
def __init__(self, *args, **kwargs): """ Inicialize first values for atributes: id, created_at, updated_at """ if not kwargs: # Here goes an exeption # What if kwargs is empty? self.id = str(uuid4()) self.created_at = datetime.utcnow() self.updated_at = datetime.utcnow() if args: storage.new(self) else: self.__dict__ = kwargs if "__class__" in self.__dict__.keys(): self.__dict__.pop("__class__") formato = "%Y-%m-%dT%H:%M:%S.%f" self.updated_at = datetime.strptime(self.updated_at, formato) self.created_at = datetime.strptime(self.created_at, formato)
def test_reload(self): """Test reload method. """ for k, v in TestFileStorage.models.items(): new_obj = v() no_id = new_obj.id storage.new(new_obj) storage.reload() inin = "{}.{}".format(k, no_id) self.assertTrue(inin in FileStorage._FileStorage__objects) self.assertIsInstance(storage, FileStorage) with self.assertRaises(TypeError) as err: storage.reload("devil's", "trill") msg = "reload() takes 1 positional argument but 3 were given" self.assertEqual(str(err.exception), msg) with self.assertRaises(TypeError) as err: FileStorage.reload() msg = "reload() missing 1 required positional argument: 'self'" self.assertEqual(str(err.exception), msg)
def do_create(self, args): """ Create an object of any class""" # space " chars to manage data args = args.replace('"', '\"') # get class and arguments separated args = self.split_args(args) # assing class and arguments as a dict class_name = args[0] args_dict = self.validate_dict(self.get_dict(args[1])) if class_name not in HBNBCommand.classes: print("** class doesn't exist **") return # create new instance new_instance = HBNBCommand.classes[class_name](**args_dict) # save changes storage.new(new_instance) storage.save() print(new_instance.id)
def __init__(self, *args, **kwargs): """ Init """ if len(kwargs) != 0: """ Use dictionary to create an instance if given """ for key, value in kwargs.items(): if key == '__class__': setattr(self, key, type(self)) elif key == 'created_at' or key == 'updated_at': """ Converts datetime string to datetime format """ setattr(self, key, dt.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")) else: setattr(self, key, value) else: """ If no dictionary is given, create a new instance with randomly generated id and current time """ self.id = str(uuid.uuid4()) self.created_at = dt.now() self.updated_at = self.created_at from models.__init__ import storage storage.new(self)
def __init__(self, *args, **kwargs): """ Initiating the BaseModel class to be able to accept arguments Converting self.created_at and self.updated_at into datetime objects if the incoming argument is a dictionary If they aren't a dictionary, call a function that turns them into a dictionary. """ formatt = '%Y-%m-%d %H:%M:%S.%f' switch = 0 for arg in args: if type(arg) is dict: switch = 1 self.created_at = datetime.strptime(arg['created_at'], formatt) self.updated_at = datetime.strptime(arg['updated_at'], formatt) self.__dict__ = arg if switch == 0: self.created_at = datetime.now() self.id = str(uuid4()) from models.__init__ import storage storage.new(self)
def do_create(self, args): """ Create an object of any class""" if not args: print("** class name missing **") return params = args.split() if params[0] not in HBNBCommand.classes: print("** class doesn't exist **") return elif len(params) == 1: new_instance = HBNBCommand.classes[params[0]]() print(new_instance.id) storage.new(new_instance) storage.save() else: new_instance = HBNBCommand.classes[params[0]]() for thePs in params[1:]: something = thePs.split("=", 1) key = something[0] if len(something) > 1: value = something[1] else: continue if len(something) > 1: number = value.split(".") if checkInt(value, 1): new_instance.__dict__[key] = int(value) elif (len(number) > 1 and checkInt(number[0], 1) and checkInt(number[1], 0)): new_instance.__dict__[key] = float(value) elif value.startswith('"') and value.endswith('"'): noQuote = value[1:-1] if escapedQuotes(noQuote): noQuote = noQuote.replace('_', ' ') noQuote = noQuote.replace('\"', '"') new_instance.__dict__[key] = noQuote print(new_instance.id) storage.new(new_instance) storage.save()
def do_create(self, args): """ Create an object of any class""" s2 = args.split() if len(s2) == 0: print("** class name missing **") return elif s2[0] not in HBNBCommand.classes: print("** class doesn't exist **") return s3 = s2[1:len(s2)] if (len(s2) > 1): new_instance = HBNBCommand.classes[s2[0]]() storage.new(new_instance) storage.save() print(new_instance.id) for i in s3: s4 = i.split('=') key = s4[0] value = s4[1] if value.isnumeric(): pass elif value[0] != '"' and value[-1] != '"': try: float(value) except ValueError: continue elif value[0] == '"' and value[-1] == '"': value = value.replace('_', ' ') else: continue update_args = s2[0] + " " + new_instance.id +\ " " + key + " " + value self.do_update(update_args) return new_instance = HBNBCommand.classes[s2[0]]() storage.new(new_instance) storage.save() print(new_instance.id) storage.save()
def test_save(self): """Test save method. """ a = 0 for k, v in TestFileStorage.models.items(): new_obj = v() storage.new(new_obj) storage.save() with open("file.json", mode="r") as file: self.assertIsInstance(json.load(file), dict) a = 1 self.assertTrue(a == 1) with self.assertRaises(TypeError) as err: storage.save("devil's", "trill") msg = "save() takes 1 positional argument but 3 were given" self.assertEqual(str(err.exception), msg) with self.assertRaises(TypeError) as err: FileStorage.save() msg = "save() missing 1 required positional argument: 'self'" self.assertEqual(str(err.exception), msg)
def do_create(self, args): """ Create an object of any class""" args = args.partition(" ") if not args[0]: print("** class name missing **") return elif args[0] not in HBNBCommand.classes: print("** class doesn't exist **") return new_instance = HBNBCommand.classes[args[0]]() if args[2]: kwargs = args[2].split() for v in kwargs: res = v.partition('=') neg_flag = 1 if res[2][0] == '-': neg_flag = -1 if res[2][0] == '"': string = res[2][1:-1] string = string.replace("_", " ") setattr(new_instance, res[0], string) elif neg_flag < 0 and res[2][1].isnumeric(): if '.' in res[2]: num = float(res[2]) else: num = int(res[2]) setattr(new_instance, res[0], num) elif res[2][0].isnumeric(): if '.' in res[2]: num = float(res[2]) else: num = int(res[2]) setattr(new_instance, res[0], num) else: pass storage.new(new_instance) storage.save() print(new_instance.id)
def do_create(self, args): """ Create an object of any class""" new_args = {} list_args = args.split() for n in list_args[1:]: n = n.split("=") new_args[n[0]] = n[1] if not list_args: print("** class name missing **") return if list_args[0] not in HBNBCommand.classes: print("** class doesn't exist **") return new_instance = HBNBCommand.classes[list_args[0]]() storage.new(new_instance) storage.save() print(new_instance.id) storage.save()
def do_create(self, args): """ Create an object of any class""" args = args.split() # print(args) if not args: print("** class name missing **") return elif args[0] not in HBNBCommand.classes: print("** class doesn't exist **") return new_instance = HBNBCommand.classes[args[0]]() for i in range(1, len(args)): if (args[i].count("=") == 1): attribute = args[i].split('=') if type(attribute[0] == str): if (attribute[1].count('"') == 2): if (attribute[1].count('_') > 0): attribute[1] = attribute[1].replace('_', ' ') # self.do_update("{} {} {} {}".format( # new_instance.__class__.__name__, # new_instance.id, attribute[0], attribute[1])) new_instance.__dict__.update( {attribute[0]: attribute[1].strip('"')}) elif (attribute[1].replace('.', '', 1).isdigit() or attribute[1].replace('.', '', 1).replace( '-', '', 1)): if attribute[1].isdigit(): new_instance.__dict__.update( {attribute[0]: int(attribute[1])}) else: new_instance.__dict__.update( {attribute[0]: float(attribute[1])}) # self.do_update("{} {} {} {}".format( # new_instance.__class__.__name__, # new_instance.id, attribute[0], attribute[1])) # new_instance.__dict__.update({attribute[0]:attribute[1]}) storage.new(new_instance) storage.save() print(new_instance.id)
def do_create(self, args): """ Create an object of any class""" l_args = sh_split(args) class_name = l_args[0] if not class_name: print("** class name missing **") return elif class_name not in HBNBCommand.classes: print("** class doesn't exist **") return d = {} for element in l_args[1:]: # seperating key and value for kwargs key_v = element.split("=") if HBNBCommand.types.get(key_v[0], "not found") != "not found": d[key_v[0]] = HBNBCommand.\ types[key_v[0]](key_v[1].replace('"', '').replace("_", ' ')) new_instance = HBNBCommand.classes[class_name]() new_instance.__dict__.update(**d) storage.new(new_instance) storage.save() print(new_instance.id)
def do_create(self, args): """ Create an object of any class""" lt0 = args.split(" ") # ---Creating a list with all the arguments--- lt1 = [] # ---Empty list for add only valid arguments--- for i in range(1, len(lt0)): if "=" in lt0[i]: lt1.append(lt0[i]) str1 = "=".join(lt1) lt2 = str1.split("=") it = iter(lt2[:]) dct1 = dict(zip(it, it)) # ---dictionary with all items--- dct2 = {} # ---empty dictionary for add only valid items--- for key, value in dct1.items(): if value != value.strip('"'): stripvalue = value.strip('"') newvalue = stripvalue.replace("_", " ") dct2[key] = newvalue else: if "." in value: newvalue = float(value) dct2[key] = newvalue else: try: newvalue = int(value) dct2[key] = newvalue except: pass if not lt0[0]: print("** class name missing **") return elif lt0[0] not in HBNBCommand.classes: print("** class doesn't exist **") # print(type(dct1['name'])) return new_instance = HBNBCommand.classes[lt0[0]](**dct2) storage.new(new_instance) print(new_instance.id) storage.save()