-
Notifications
You must be signed in to change notification settings - Fork 8
/
file_storage.py
executable file
·49 lines (42 loc) · 1.55 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
#!/usr/bin/python3
"""Defines the FileStorage class."""
import json
from models.base_model import BaseModel
from models.user import User
from models.state import State
from models.city import City
from models.place import Place
from models.amenity import Amenity
from models.review import Review
class FileStorage:
"""Represent an abstracted storage engine.
Attributes:
__file_path (str): The name of the file to save objects to.
__objects (dict): A dictionary of instantiated objects.
"""
__file_path = "file.json"
__objects = {}
def all(self):
"""Return the dictionary __objects."""
return FileStorage.__objects
def new(self, obj):
"""Set in __objects obj with key <obj_class_name>.id"""
ocname = obj.__class__.__name__
FileStorage.__objects["{}.{}".format(ocname, obj.id)] = obj
def save(self):
"""Serialize __objects 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):
"""Deserialize the JSON file __file_path to __objects, if it exists."""
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