Repository navigation
Expand file tree
/
Copy pathlike_db.py
More file actions
91 lines (82 loc) · 2.65 KB
/
Copy pathlike_db.py
File metadata and controls
91 lines (82 loc) · 2.65 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
82
83
84
85
86
87
88
89
90
91
import json
#Create Like counting class
class LikeDB:
def __init__(self, db_path):
#Initialize the database
#Open the database file if it exists, otherwise create a new database file
self.db_path = db_path
try:
with open(db_path, 'r') as f:
self.db = json.load(f)
except FileNotFoundError:
self.db = {}
#Save the database to the database file
with open(db_path, 'w') as f:
json.dump(self.db, f)
def save(self):
with open(self.db_path, 'w') as f:
json.dump(self.db, f)
def all_likes(self):
"""Counts all users likes
returns
all users likes
"""
likes = 0
if self.db:
for user in self.db:
likes += self.db[user]['like']
return likes
def all_dislikes(self):
"""Counts all users dislikes
returns
all users dislikes
"""
dislikes = 0
if self.db:
for user in self.db:
dislikes += self.db[user]['dislike']
return dislikes
#Add a like to the database
def add_like(self, user_id:str)->dict:
'''
Add a like to the database
args:
user_id: The user id of the user who liked the post
returns:
The number of likes and dislikes for the post
'''
if self.db.get(user_id):
if self.db[user_id]['like'] == 0:
self.db[user_id]['like'] = 1
if self.db[user_id]['dislike'] == 1:
self.db[user_id]['dislike'] = 0
elif self.db[user_id]['like'] == 1:
self.db[user_id]['like'] = 0
else:
self.db[user_id] = {
'like': 1,
'dislike': 0
}
self.save()
#Add a dislike to the database
def add_dislike(self, user_id:str)->dict:
'''
Add a dislike to the database
args:
user_id: The user id of the user who disliked the post
returns:
The number of likes and dislikes for the post
'''
if self.db.get(user_id):
if self.db[user_id]['dislike'] == 0:
self.db[user_id]['dislike'] = 1
if self.db[user_id]['like'] == 1:
self.db[user_id]['like'] = 0
elif self.db[user_id]['dislike'] == 1:
self.db[user_id]['dislike'] = 0
else:
self.db[user_id] = {
'like': 0,
'dislike': 1
}
self.save()