-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathfile_storage.py
More file actions
executable file
·81 lines (73 loc) · 2.35 KB
/
file_storage.py
File metadata and controls
executable file
·81 lines (73 loc) · 2.35 KB
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
#!/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
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
"""
if not cls:
return self.__objects
else:
dic_result = {}
for key, val in self.__objects.items():
name = key.split('.')
if name[0] == cls.__name__:
dic_result.update({key: val})
return dic_result
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 obj from __objects if it’s inside"""
if obj:
for key in self.__objects:
idn = key.split('.')
if obj.id == idn[1]:
del self.__objects[key]
break
self.save()
def close(self):
"""
Calls reload() method for deserializing the JSON file to objects
"""
self.reload()