-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
61 lines (51 loc) · 1.74 KB
/
database.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
import json
import threading
import time
from server_client import Client, Message
class Database:
def __init__(self, filename):
self.filename = filename
self.data = {}
self.lock = threading.Lock()
self.load_from_file()
def load_from_file(self):
try:
with open(self.filename, "r") as f:
self.data = json.load(f)
for key in self.data:
self.data[key] = Client.from_dict(self.data[key])
except FileNotFoundError:
with open(self.filename, "w") as f:
json.dump({}, f)
with open(self.filename, "r") as f:
self.data = json.load(f)
except json.JSONDecodeError:
with open(self.filename, "w") as f:
json.dump({}, f)
with open(self.filename, "r") as f:
self.data = json.load(f)
def save_to_file(self):
with self.lock:
with open(self.filename, "w") as f:
json.dump(self.data, f, default=self.serialize_custom_objects)
def get(self, key):
return self.data.get(key)
def set(self, key, value):
self.data[str(key)] = value
self.save_to_file()
def add_message(self, key, message):
if self.data.get(key):
self.data[key].add_message(message)
else:
client = Client()
client.add_message(message)
self.data[key] = client
self.save_to_file()
def pop(self, key):
pop = self.data.pop(str(key), None)
self.save_to_file()
return pop
def serialize_custom_objects(self, obj):
if isinstance(obj, (Client, Message)):
return obj.to_dict()
return None