-
Notifications
You must be signed in to change notification settings - Fork 1
/
file_storage.py
80 lines (72 loc) · 2.26 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
74
75
76
77
78
79
80
#!/usr/bin/python3
"""This is the file storage class for AirBnB"""
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.amenity import Amenity
from models.place import Place
from models.review import Review
import shlex
class FileStorage:
"""This class serializes instances to a JSON file and
deserializes JSON file to instances
Attributes:
__file_path: path to the JSON file
__objects: objects will be stored
"""
__file_path = "file.json"
__objects = {}
def all(self, cls=None):
"""returns a dictionary
Return:
returns a dictionary of __object
"""
dic = {}
if cls:
dictionary = self.__objects
for key in dictionary:
partition = key.replace('.', ' ')
partition = shlex.split(partition)
if (partition[0] == cls.__name__):
dic[key] = self.__objects[key]
return (dic)
else:
return self.__objects
def new(self, obj):
"""sets __object to given obj
Args:
obj: given object
"""
if obj:
key = "{}.{}".format(type(obj).__name__, obj.id)
self.__objects[key] = obj
def save(self):
"""serialize the file path to JSON file path
"""
my_dict = {}
for key, value in self.__objects.items():
my_dict[key] = value.to_dict()
with open(self.__file_path, 'w', encoding="UTF-8") as f:
json.dump(my_dict, f)
def reload(self):
"""serialize the file path to JSON file path
"""
try:
with open(self.__file_path, 'r', encoding="UTF-8") as f:
for key, value in (json.load(f)).items():
value = eval(value["__class__"])(**value)
self.__objects[key] = value
except FileNotFoundError:
pass
def delete(self, obj=None):
""" delete an existing element
"""
if obj:
key = "{}.{}".format(type(obj).__name__, obj.id)
del self.__objects[key]
def close(self):
""" calls reload()
"""
self.reload()