forked from justinmajetich/AirBnB_clone
-
Notifications
You must be signed in to change notification settings - Fork 1
/
file_storage.py
73 lines (64 loc) · 2.29 KB
/
file_storage.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
#!/usr/bin/python3
"""This module defines a class to manage file storage for hbnb clone"""
import json
class FileStorage:
"""This class manages storage of hbnb models in JSON format"""
__file_path = 'file.json'
__objects = {}
def all(self, cls=None):
"""Returns a dictionary of models currently in storage"""
if cls is None:
return self.__objects
cls_name = cls.__name__
dct = {}
for key in self.__objects.keys():
if key.split('.')[0] == cls_name:
dct[key] = self.__objects[key]
return dct
def new(self, obj):
"""Adds new object to storage dictionary"""
self.__objects.update(
{obj.to_dict()['__class__'] + '.' + obj.id: obj}
)
def save(self):
"""Saves storage dictionary to file"""
with open(self.__file_path, 'w') as f:
temp = {}
temp.update(self.__objects)
for key, val in temp.items():
temp[key] = val.to_dict()
json.dump(temp, f)
def reload(self):
"""Loads storage dictionary from file"""
from models.base_model import BaseModel
from models.user import User
from models.place import Place
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.review import Review
classes = {
'BaseModel': BaseModel, 'User': User, 'Place': Place,
'State': State, 'City': City, 'Amenity': Amenity,
'Review': Review
}
try:
temp = {}
with open(self.__file_path, 'r') as f:
temp = json.load(f)
for key, val in temp.items():
self.all()[key] = classes[val['__class__']](**val)
except FileNotFoundError:
pass
def delete(self, obj=None):
''' deletes the object obj from the attribute
__objects if it's inside it
'''
if obj is None:
return
obj_key = obj.to_dict()['__class__'] + '.' + obj.id
if obj_key in self.__objects.keys():
del self.__objects[obj_key]
def close(self):
"""Call the reload method"""
self.reload()