-
Notifications
You must be signed in to change notification settings - Fork 1
/
file_storage.py
executable file
·45 lines (39 loc) · 1.4 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
#!/usr/bin/python3
"""The file storage Class"""
import json
from models.base_model import BaseModel
from models.user import User
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.amenity import Amenity
class FileStorage:
"""An abstract file storage engine."""
__file_path = "file.json"
__objects = {}
def all(self):
"""Return dictionary __objects."""
return FileStorage.__objects
def new(self, obj):
"""Set in __objects the obj with key <obj_class_name>.id"""
ocname = obj.__class__.__name__
FileStorage.__objects["{}.{}".format(ocname, obj.id)] = obj
def save(self):
"""Serialize __object to the JSON file __file_path"""
odict = FileStorage.__objects
objdict = {obj: odict[obj].to_dict() for obj in odict.keys()}
with open(FileStorage.__file_path, "w") as f:
json.dump(objdict, f)
def reload(self):
"""Deserializes the JSON file to __objects,
if it exits, else nothing"""
try:
with open(FileStorage.__file_path) as f:
objdict = json.load(f)
for o in objdict.values():
cls_name = o["__class__"]
del o["__class__"]
self.new(eval(cls_name)(**o))
except FileNotFoundError:
return