-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsave_data.py
77 lines (69 loc) · 3.02 KB
/
save_data.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
from tkinter import messagebox
from json import dump, load, JSONDecodeError
class SaveData:
def __init__(self, website, email, password):
self.website = website
self.email = email
self.password = password
self.data = {}
def get_data(self)->None:
"""_Process data from Tkinter Entry field and save them into the data dictionary_
"""
self.entered_website = self.website.get().title()
self.data[self.entered_website] = {"email":self.email.get(),"password": self.password.get()}
def save_data_file(self)->None:
"""_Write the website, email and password to data text file_
"""
self.get_data()
if self.is_website_or_password_empty():
messagebox.showerror(title="Missing Fields", message="Website and Password cannot be empty")
else:
if self.is_ready_to_save():
self.save_data_to_json()
def clear_data(self)->None:
"""_Clear the content of the input fields_
"""
self.website.delete(0, 'end')
self.password.delete(0, 'end')
def is_website_or_password_empty(self)-> bool:
"""_Check whether password and website are empty_
Returns:
bool: _True if website or password is empty otherwise False_
"""
return len(self.entered_website)==0 or len(self.data[self.entered_website]['password']) == 0
def is_ready_to_save(self)->bool:
"""_Confirm user wishes to save the given info_
Returns:
bool: _True for ok or False for cancel_
"""
return messagebox.askokcancel(title="Save", message=f"Are you sure you want to save\n Website: {self.entered_website} \n Password: {self.data[self.entered_website]['password']}")
def save_data_to_json(self)-> None:
"""_Read json file contents if it exist, update with new data and then save or create a new
json file and save to it_
"""
try:
with open("data.json","r") as file:
old_data = load(file)
with open("data.json", "w") as file:
old_data.update(self.data)
dump(old_data, file ,indent=4)
except (FileNotFoundError, JSONDecodeError):
with open("data.json", "w") as file:
dump(self.data, file, indent=4)
finally:
self.clear_data()
def search(self)->None:
website = self.website.get().title()
try:
with open("data.json", "r") as file:
data = load(file)
except FileNotFoundError as e:
messagebox.showinfo(message=f"{e} Doesn't Exist")
else:
try:
website_data = data[website]
except KeyError as key:
messagebox.showinfo(message=f"{key} Not Found", )
else:
messagebox.showinfo(message=f"Email: {website_data['email']} \nPassword: {website_data['password']}", title=f"{website}")
self.website.delete(0, 'end')