Day 29 & 30 - JSON & ERROR & Password Manager


Posted by pei_______ on 2022-05-10

learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022


Json

  1. Write
    json.dump(input_data, output_file)

  2. Read
    json.load(inptput_file)

  3. Update
    json.update(append_data)


常見Error

FileNotFoundError 開啟不存在的檔案
KeyError 尋找補存在的key
IndexError 尋找超過List長度的資料
TypeError 不同型態資料混用

try: 
    (do something)

except TypeError: 
    (if counter error)

else:
    (what else to do)

finally: 
    (no matter what happen, finally do)

raise TypeError("raise your own error")

Password Manager Project

Constant

from tkinter import *
from tkinter import messagebox
from random import choice, randint, shuffle
import pyperclip
import json

generate_password()

def generate_password():
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

    password_letters = [choice(letters) for _ in range(randint(8, 10))]
    password_symbols = [choice(symbols) for _ in range(randint(2, 4))]
    password_numbers = [choice(numbers) for _ in range(randint(2, 4))]

    password_list = password_letters + password_symbols + password_numbers

    shuffle(password_list)

    password = "".join(password_list)
    password_entry.insert(END, password)
    pyperclip.copy(password)

save()

def save():

    website = website_entry.get().lower()
    email = email_entry.get()
    password = password_entry.get()
    new_data = {
        website: {
            "email": email,
            "password": password,
        }
    }

    if website == '' or email == '' or password == '':
        messagebox.showinfo(title="Oops", message="Please don't leave any fields empty!")
    else:
        try:
            with open("data.json", "r") as file:
                # Reading old data
                data = json.load(file)

        except FileNotFoundError:
            with open("data.json", "w") as file:
                json.dump(new_data, file, indent=4)
        else:
            # Updating old data with new data
            data.update(new_data)

            with open("data.json", "w") as file:
                # Saving updated data
                json.dump(data, file, indent=4)

        finally:
            website_entry.delete(0, END)
            password_entry.delete(0, END)

find_password()

def find_password():
    website = website_entry.get().lower()

    try:
        with open("data.json", "r") as file:
            data = json.load(file)

    except FileNotFoundError:
        messagebox.showinfo(title="Oops", message="Please save a password for start")

    else:
        if website in data:
            email = data[website]["email"]
            password = data[website]["password"]
            messagebox.showinfo(title=website, message=f"email: {email}\npassword: {password}")
        else:
            messagebox.showinfo(title="Oops", message=f"There's no info")

UI SETUP

window = Tk()
window.title('Password Manager')
window.config(padx=40, pady=40)
window.minsize()

logo_img = PhotoImage(file='logo.png')
canvas = Canvas(width=200, height=200)
canvas.create_image(100, 100, image=logo_img)
canvas.grid(row=1, column=2, sticky="W")

website_label = Label(text="Website:  ")
website_label.grid(row=2, column=1)
email_label = Label(text="Email/Username:  ")
email_label.grid(row=3, column=1)
password_label = Label(text="Password:  ")
password_label.grid(row=4, column=1)


website_entry = Entry(width=18)
website_entry.focus()
website_entry.grid(row=2, column=2, sticky="EW")
email_entry = Entry(width=35)
email_entry.grid(row=3, column=2, columnspan=2, sticky="EW")
email_entry.insert(END, "zxc61224@gmail.com")
password_entry = Entry(width=18)
password_entry.grid(row=4, column=2, sticky="EW")

search_button = Button(text="Search", width=15, command=find_password)
search_button.grid(row=2, column=3)
generate_password_button = Button(text="Generate Password", command=generate_password)
generate_password_button.grid(row=4, column=3)
add_button = Button(text="Add", width=36, command=save)
add_button.grid(row=5, column=2, columnspan=2, sticky="EW")

window.mainloop()

#Python #課堂筆記 #100 Days of Code







Related Posts

學習 Git (8) - Tag 標籤

學習 Git (8) - Tag 標籤

Spring boot系列(六)Log

Spring boot系列(六)Log

Filter 應用CORS

Filter 應用CORS


Comments