-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_storage.py
73 lines (62 loc) · 2.19 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
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
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:
if type(cls) == str:
cls = classes[cls]
class_name = cls.__name__
new_dict = {k: v for (k, v) in FileStorage.__objects.items()
if class_name in k}
return new_dict
else:
return FileStorage.__objects
def new(self, obj):
"""Adds new object to storage dictionary"""
self.all().update({obj.to_dict()['__class__'] + '.' + obj.id: obj})
def save(self):
"""Saves storage dictionary to file"""
with open(FileStorage.__file_path, 'w') as f:
temp = {}
temp.update(FileStorage.__objects)
for key, val in temp.items():
temp[key] = val.to_dict()
json.dump(temp, f)
def reload(self):
"""Loads storage dictionary from file"""
classes = {
'BaseModel': BaseModel, 'User': User, 'Place': Place,
'State': State, 'City': City, 'Amenity': Amenity,
'Review': Review
}
try:
temp = {}
with open(FileStorage.__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):
"""delete obj from __objects"""
if obj is None:
pass
else:
self.all().pop(obj.__class__.__name__ + "." + obj.id)
def close(self):
"""
Deserializes the python objects
"""
self.reload()