-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_storage.py
109 lines (96 loc) · 2.87 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/python3
'''
Define class FileStorage
'''
import json
import models
class FileStorage:
'''
Serializes instances to JSON file and deserializes to JSON file.
'''
__file_path = "file.json"
__objects = {}
def all(self, cls=None):
'''
Return the dictionary
'''
new_dict = {}
if cls is None:
return self.__objects
if cls != "":
for k, v in self.__objects.items():
if cls == k.split(".")[0]:
new_dict[k] = v
return new_dict
else:
return self.__objects
def new(self, obj):
'''
Set in __objects the obj with key <obj class name>.id
Aguments:
obj : An instance object.
'''
key = str(obj.__class__.__name__) + "." + str(obj.id)
value_dict = obj
FileStorage.__objects[key] = value_dict
def save(self):
'''
Serializes __objects attribute to JSON file.
'''
objects_dict = {}
for key, val in FileStorage.__objects.items():
objects_dict[key] = val.to_dict()
with open(FileStorage.__file_path, mode='w', encoding="UTF8") as fd:
json.dump(objects_dict, fd)
def reload(self):
'''
Deserializes the JSON file to __objects.
'''
try:
with open(FileStorage.__file_path, encoding="UTF8") as fd:
FileStorage.__objects = json.load(fd)
for key, val in FileStorage.__objects.items():
class_name = val["__class__"]
class_name = models.classes[class_name]
FileStorage.__objects[key] = class_name(**val)
except FileNotFoundError:
pass
def delete(self, obj=None):
'''
Deletes an obj
'''
if obj is not None:
key = str(obj.__class__.__name__) + "." + str(obj.id)
FileStorage.__objects.pop(key, None)
self.save()
def close(self):
'''
Deserialize JSON file to objects
'''
self.reload()
def get(self, cls, id):
'''
gets an object
Args:
cls (str): class name
id (str): object ID
Returns:
an object based on class name and its ID
'''
obj_dict = self.all(cls)
for k, v in obj_dict.items():
matchstring = cls + '.' + id
if k == matchstring:
return v
return None
def count(self, cls=None):
'''
counts number of objects in a class (if given)
Args:
cls (str): class name
Returns:
number of objects in class, if no class name given
return total number of objects in database
'''
obj_dict = self.all(cls)
return len(obj_dict)