-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
72 lines (56 loc) · 1.76 KB
/
database.py
File metadata and controls
72 lines (56 loc) · 1.76 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
import json
class Database:
"""
A database class for storing and managing user data.
Args:
filename (str): The name of the JSON file used to store data.
Attributes:
filename (str): The name of the JSON file used to store data.
data (dict): A dictionary to store user data.
Methods:
load_data(): Load user data from the JSON file.
save_data(): Save user data to the JSON file.
get_user_by_username(username): Get user data by username.
"""
def __init__(self, filename):
"""
Initialize the Database.
Args:
filename (str): The name of the JSON file used to store data.
"""
self.filename = filename
self.data = self.load_data()
def load_data(self):
"""
Load user data from the JSON file.
Returns:
dict: The loaded user data as a dictionary.
"""
try:
with open(self.filename, 'r') as file:
data = json.load(file)
except FileNotFoundError:
data = {}
print("File not found!")
return data
def save_data(self):
"""
Save user data to JSON file
"""
with open(self.filename, 'w') as file:
json.dump(self.data, file, indent=4)
def get_user_by_username(self, username):
"""
Get user data by username.
Args:
username (str): The username of the user to retrieve.
Returns:
dict or None: User data if found, None if not found.
"""
if username in self.data:
return self.data[username]
return None
if __name__ == "__main__":
db = Database("users.json")
db.data.append('a')
print(db.data)