forked from feliciahsieh/AirBnB_clone_v3
-
Notifications
You must be signed in to change notification settings - Fork 65
/
console.py
executable file
·181 lines (163 loc) · 6.25 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
#!/usr/bin/python3
""" console """
import cmd
from datetime import datetime
import models
from models.amenity import Amenity
from models.base_model import BaseModel
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.user import User
import shlex # for splitting the line along spaces except in double quotes
import re
classes = {"Amenity": Amenity, "BaseModel": BaseModel, "City": City,
"Place": Place, "Review": Review, "State": State, "User": User}
class HBNBCommand(cmd.Cmd):
""" HBNH console """
prompt = '(hbnb) '
def do_EOF(self, arg):
"""Exits console"""
return True
def emptyline(self):
""" overwriting the emptyline method """
return False
def do_quit(self, arg):
"""Quit command to exit the program"""
return True
def do_create(self, arg):
"""Creates a new instance of a class
Command syntax: create <Class name> <param 1> <param 2> <param 3>...
Param syntax: <key name>=<value>
Value syntax:
string: "<value>"
Internal double quotes should be escaped. Spaces can be
represented using `_` and will be replaced by spaces.
float: <unit>.<decimal>
Unit or decimal may be missing.
int: <number>
Decimal integer.
Any parameter that does not fit this pattern will be ignored.
"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
return False
if args[0] not in classes:
print("** class doesn't exist **")
return False
else:
kwargs = {}
for arg in args[1:]:
match = re.fullmatch('(?P<key>[a-zA-Z_]\w*)=(?:'
'(?P<int>\d+)|'
'(?P<float>\d*\.\d*)|'
'(?P<string>.*))',
arg)
match = match.groupdict()
if match['string']:
kwargs[match['key']] = match['string'].replace('_', ' ')
elif match['float']:
if match['float'] == '.':
continue
kwargs[match['key']] = float(match['float'])
else:
kwargs[match['key']] = int(match['int'])
instance = classes[args[0]](**kwargs)
try:
instance.save()
except Exception as e:
print("** could not save [{}] object **".format(args[0]))
print(e)
return False
else:
print(instance.id)
def do_show(self, arg):
"""Prints an instance as a string based on the class and id"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
return False
if args[0] in classes:
if len(args) > 1:
key = args[0] + "." + args[1]
if key in models.storage.all():
print(models.storage.all()[key])
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")
def do_destroy(self, arg):
"""Deletes an instance based on the class and id"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
elif args[0] in classes:
if len(args) > 1:
key = args[0] + "." + args[1]
if key in models.storage.all():
models.storage.all()[key].delete()
models.storage.save()
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")
def do_all(self, arg):
"""Prints string representations of instances"""
args = shlex.split(arg)
obj_list = []
if len(args) == 0:
for value in models.storage.all().values():
obj_list.append(str(value))
elif args[0] in classes:
for key in models.storage.all():
if key.startswith(args[0]):
obj_list.append(str(models.storage.all()[key]))
else:
print("** class doesn't exist **")
return False
print(obj_list)
def do_update(self, arg):
"""Update an instance based on the class name, id, attribute & value"""
args = shlex.split(arg)
integers = ["number_rooms", "number_bathrooms", "max_guest",
"price_by_night"]
floats = ["latitude", "longitude"]
if len(args) == 0:
print("** class name missing **")
elif args[0] in classes:
if len(args) > 1:
k = args[0] + "." + args[1]
if k in models.storage.all():
if len(args) > 2:
if len(args) > 3:
if args[0] == "Place":
if args[2] in integers:
try:
args[3] = int(args[3])
except:
args[3] = 0
elif args[2] in floats:
try:
args[3] = float(args[3])
except:
args[3] = 0.0
setattr(models.storage.all()[k], args[2], args[3])
models.storage.all()[k].save()
else:
print("** value missing **")
else:
print("** attribute name missing **")
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")
if __name__ == '__main__':
HBNBCommand().cmdloop()