-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile_storage.py
45 lines (37 loc) · 1.06 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
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
# import models
class FileStorage():
"""Serializes to JSON file and deserializes JSON file to instances"""
#Private class Attributes
__file_path = "file.json"
__objects = {}
# Public Istance Methods
def all(self):
"""Returns Dictionaary Objects"""
return self.__objects
def new(self, obj):
""" """
key = f"{obj.__class__.__name__}.{obj.id}"
self.__objects[key] = obj
def save(self):
with open(self.__file_path, "w", encoding="utf-8") as f:
d = {k: v.to_dict() for k, v in self.__objects.items()}
json.dump(d, f)
def reload(self):
try:
with open(self.__file_path, "r", encoding="utf-8") as f:
obj_dict = json.load(f)
for o in obj_dict.values():
cls_name = o["__class__"]
del o["__class__"]
self.new(eval(f"{cls_name}")(**o))
except FileNotFoundError:
return