-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsole.py
272 lines (249 loc) · 8.82 KB
/
console.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/python3
"""This is the console for AirBnB"""
import cmd
from models import storage
from datetime import datetime
from models.base_model import BaseModel
from models.user import User
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.review import Review
from shlex import split
class HBNBCommand(cmd.Cmd):
"""this class is entry point of the command interpreter
"""
prompt = "(hbnb) "
all_classes = {"BaseModel", "User", "State", "City",
"Amenity", "Place", "Review"}
def emptyline(self):
"""Ignores empty spaces"""
pass
def do_quit(self, line):
"""Quit command to exit the program"""
return True
def do_EOF(self, line):
"""Quit command to exit the program at end of file"""
return True
def do_create(self, args):
"""Creates a new instance of BaseModel.
Exceptions:
SyntaxError: when there is no args given
NameError: when there is no object taht has the name
"""
try:
if not args:
raise SyntaxError()
splittedArgs = args.split(" ")
inst = eval("{}()".format(splittedArgs[0]))
for commandArg in splittedArgs[1:]:
param = commandArg.split("=")
key = param[0]
value = param[1].replace("_", " ")
if hasattr(inst, key):
try:
setattr(inst, key, eval(value))
except Exception:
pass
inst.save()
print("{}".format(inst.id))
except SyntaxError:
print("** class name missing **")
except NameError:
print("** class doesn't exist **")
except IndexError:
pass
def do_show(self, line):
"""Prints the string representation of an instance
Exceptions:
SyntaxError: when there is no args given
NameError: when there is no object taht has the name
IndexError: when there is no id given
KeyError: when there is no valid id given
"""
try:
if not line:
raise SyntaxError()
my_list = line.split(" ")
if my_list[0] not in self.all_classes:
raise NameError()
if len(my_list) < 2:
raise IndexError()
objects = storage.all()
key = my_list[0] + '.' + my_list[1]
if key in objects:
print(objects[key])
else:
raise KeyError()
except SyntaxError:
print("** class name missing **")
except NameError:
print("** class doesn't exist **")
except IndexError:
print("** instance id missing **")
except KeyError:
print("** no instance found **")
def do_destroy(self, line):
"""Deletes an instance based on the class name and id
Exceptions:
SyntaxError: when there is no args given
NameError: when there is no object taht has the name
IndexError: when there is no id given
KeyError: when there is no valid id given
"""
try:
if not line:
raise SyntaxError()
my_list = line.split(" ")
if my_list[0] not in self.all_classes:
raise NameError()
if len(my_list) < 2:
raise IndexError()
objects = storage.all()
key = my_list[0] + '.' + my_list[1]
if key in objects:
del objects[key]
storage.save()
else:
raise KeyError()
except SyntaxError:
print("** class name missing **")
except NameError:
print("** class doesn't exist **")
except IndexError:
print("** instance id missing **")
except KeyError:
print("** no instance found **")
def do_all(self, line):
"""Prints all string representation of all instances
Exceptions:
NameError: when there is no object taht has the name
"""
objects = storage.all()
my_list = []
if not line:
for key in objects:
my_list.append(objects[key])
print(my_list)
return
try:
args = line.split(" ")
if args[0] not in self.all_classes:
raise NameError()
for key in objects:
name = key.split('.')
if name[0] == args[0]:
my_list.append(objects[key])
print(my_list)
except NameError:
print("** class doesn't exist **")
def do_update(self, line):
"""Updates an instanceby adding or updating attribute
Exceptions:
SyntaxError: when there is no args given
NameError: when there is no object taht has the name
IndexError: when there is no id given
KeyError: when there is no valid id given
AttributeError: when there is no attribute given
ValueError: when there is no value given
"""
try:
if not line:
raise SyntaxError()
my_list = split(line, " ")
if my_list[0] not in self.all_classes:
raise NameError()
if len(my_list) < 2:
raise IndexError()
objects = storage.all()
key = my_list[0] + '.' + my_list[1]
if key not in objects:
raise KeyError()
if len(my_list) < 3:
raise AttributeError()
if len(my_list) < 4:
raise ValueError()
v = objects[key]
try:
v.__dict__[my_list[2]] = eval(my_list[3])
except Exception:
v.__dict__[my_list[2]] = my_list[3]
v.save()
except SyntaxError:
print("** class name missing **")
except NameError:
print("** class doesn't exist **")
except IndexError:
print("** instance id missing **")
except KeyError:
print("** no instance found **")
except AttributeError:
print("** attribute name missing **")
except ValueError:
print("** value missing **")
def count(self, line):
"""count the number of instances of a class
"""
counter = 0
try:
my_list = split(line, " ")
if my_list[0] not in self.all_classes:
raise NameError()
objects = storage.all()
for key in objects:
name = key.split('.')
if name[0] == my_list[0]:
counter += 1
print(counter)
except NameError:
print("** class doesn't exist **")
def strip_clean(self, args):
"""strips the argument and return a string of command
Args:
args: input list of args
Return:
returns string of argumetns
"""
new_list = []
new_list.append(args[0])
try:
my_dict = eval(
args[1][args[1].find('{'):args[1].find('}')+1])
except Exception:
my_dict = None
if isinstance(my_dict, dict):
new_str = args[1][args[1].find('(')+1:args[1].find(')')]
new_list.append(((new_str.split(", "))[0]).strip('"'))
new_list.append(my_dict)
return new_list
new_str = args[1][args[1].find('(')+1:args[1].find(')')]
new_list.append(" ".join(new_str.split(", ")))
return " ".join(i for i in new_list)
def default(self, line):
"""retrieve all instances of a class and
retrieve the number of instances
"""
my_list = line.split('.')
if len(my_list) >= 2:
if my_list[1] == "all()":
self.do_all(my_list[0])
elif my_list[1] == "count()":
self.count(my_list[0])
elif my_list[1][:4] == "show":
self.do_show(self.strip_clean(my_list))
elif my_list[1][:7] == "destroy":
self.do_destroy(self.strip_clean(my_list))
elif my_list[1][:6] == "update":
args = self.strip_clean(my_list)
if isinstance(args, list):
obj = storage.all()
key = args[0] + ' ' + args[1]
for k, v in args[2].items():
self.do_update(key + ' "{}" "{}"'.format(k, v))
else:
self.do_update(args)
else:
cmd.Cmd.default(self, line)
if __name__ == '__main__':
HBNBCommand().cmdloop()