· 5 years ago · Jul 16, 2020, 06:42 PM
1
2import argparse
3from datetime import date
4import sqlite3
5from sqlite3 import Error
6
7class ContactBook:
8 conn = sqlite3.connect('contact.db')
9 c = conn.cursor()
10
11 c.execute(""" CREATE TABLE IF NOT EXISTS contacts (
12 firstname text,
13 lastname text,
14 email text,
15 phone text
16 ) """)
17
18
19
20 def __init__(self, first_name=None, last_name=None, email=None, phone=None):
21 self.first_name = first_name
22 self.last_name = last_name
23 self.email = email
24 self.phone = phone
25 self.date_created = date.today()
26
27
28
29 def get_args(self):
30 parser = argparse.ArgumentParser(description="Creating a contact book.")
31 parser.add_argument('--firstname', type=str, help='The first name of your contact')
32 parser.add_argument('--lastname', type=str, help='The last name of your contact')
33 parser.add_argument('--email', type=str, help="The email address of your contact")
34 parser.add_argument('--phone', type=str, help="The phone number of your contact")
35 parser.add_argument('--update', help="This will allow you to update a contact", action="store_true")
36 parser.add_argument('--listcontact', help="This will grab a contact you specify by first and last name and print it to the console", action="store_true")
37 parser.add_argument('--listsort', help="This will list contacts by last name in alphabetical order and print it to the console", action="store_true")
38 parser.add_argument('--all', help="Will list all of your contacts", action="store_true")
39 parser.add_argument('--deleteall', help="Will delete all your contacts", action="store_true")
40 parser.add_argument('--delete', help="This will delete a particular contact you specify", action="store_true")
41 args = parser.parse_args()
42
43
44 #print(f"this is args: {args}")
45 return args
46
47 def insert_contact(self):
48 """
49 inserts a contact into the database if it doesn't exist in the contacts table
50 """
51 contact_args = contact.get_args()
52 #print(f"this is contact_args: {contact_args}")
53 name_list = self.c.execute("SELECT * FROM contacts WHERE firstname=:firstname AND lastname=:lastname", {'firstname':contact_args.firstname, 'lastname':contact_args.lastname})
54
55 if (contact_args.firstname, contact_args.lastname, contact_args.email, contact_args.phone) not in name_list and not contact_args.all: # check if tuple is in the list, if it's not then insert it into the table
56 print("...Not in table so insert...")
57 self.c.execute("INSERT INTO contacts VALUES (:firstname, :lastname, :email, :phone)",
58 {'firstname': contact_args.firstname, 'lastname': contact_args.lastname, 'email':contact_args.email, 'phone':contact_args.phone})
59 self.conn.commit()
60 self.conn.close()
61 else:
62 print("...Contact is already in your contact book...")
63
64
65 def update_contact(self):
66 """
67 Updates the information of the contact
68 """
69 field_changed = input("Which field do you want to update? Type 'firstname','lastname','email' or 'phone > ")
70 field_changed_to = input("What do you want to change the field to? > ")
71 firstname_value = input("What is the first name of the contact you want to change? > ")
72 lastname_value = input("What is the last name of the contact you want to change? > ")
73
74 self.c.execute("""UPDATE contacts SET """ + field_changed + """=?
75 WHERE firstname = ? and lastname = ? """,
76 (field_changed_to, firstname_value, lastname_value))
77
78 self.conn.commit()
79 self.conn.close()
80
81 # TODO: this function does not loop thorugh and prompt to delete when more than one contact
82 def delete_contact(self):
83 """
84 Deletes a contact you specify
85 """
86
87 firstname_delete = input("What is the first name of the contact you want to delete? ")
88 lastname_delete = input("What is the last name of the contact you want to delete? ")
89
90 contacts_to_delete = self.c.execute("SELECT * FROM contacts WHERE firstname=? AND lastname=?",
91 (firstname_delete, lastname_delete) )
92
93 row = self.c.fetchone()
94 if row is None:
95 print(f"The contact {firstname_delete} {lastname_delete} does not exist.")
96
97 for contact in contacts_to_delete:
98 first, last, email, phone = contact
99
100 is_delete = input("Do you want to delete contact {} {} {} {} ? Type 'Yes' or 'No' > ".format(first, last, email, phone))
101 if is_delete == 'Yes' or 'yes':
102 self.c.execute("DELETE FROM contacts WHERE firstname=? AND lastname=? AND email=? AND phone=?",
103 (first, last, email, phone))
104
105 print("Your contact has been deleted.")
106
107 self.conn.commit()
108 self.conn.close()
109
110 def delete_all_contacts(self):
111 # deletes all contacts from your contact book
112 confirmation = input("Are you sure you want to delete ALL your contacts? Type 'Yes' or 'No' > ")
113 if confirmation == "Yes" or confirmation == "yes":
114 print("..You are deleting all your contacts...")
115 self.c.execute("DELETE FROM contacts")
116 self.conn.commit()
117 self.conn.close()
118 elif confirmation == "No" or confirmation == "no":
119 print("Phew, your contacts will not be deleted.")
120
121
122 def list_contacts(self):
123 """
124 Selects all the contacts in the contact book and prints them out to the console
125 """
126
127 self.c.execute("SELECT * FROM contacts")
128 contacts = self.c.fetchall()
129 for item in contacts:
130 print(item)
131
132
133 def list_contact(self):
134 """
135 Selects a contact that's specified and prints it to the console
136 """
137 firstname_contact = input("What is the first name of your contact? ")
138 lastname_contact = input("What is the last name of your contact? ")
139
140 select_contact = self.c.execute("SELECT * FROM contacts WHERE firstname=?" \
141 "AND lastname=?", (firstname_contact, lastname_contact))
142
143 row = self.c.fetchone() # gets the first row
144
145 if row is None: # if there are no results in the first row then the contact doesn't exist
146 print(f"There is no contact by the name of {firstname_contact} {lastname_contact}")
147
148 for contact in select_contact:
149 first, last, email, phone = contact
150 if first == firstname_contact and last == lastname_contact:
151 print(f"Here is your contact: {contact}")
152
153
154
155 def list_sort_by_last_name(self):
156 """
157 Sorts the contacts by last name in ascending order and prints to the console
158 """
159
160 sorted_contacts = self.c.execute("SELECT * FROM contacts ORDER BY lastname")
161
162 for contact in sorted_contacts:
163 print(contact)
164
165
166 def main(self):
167
168 args = contact.get_args()
169
170 if args.all:
171 contact.list_contacts()
172 elif args.deleteall:
173 contact.delete_all_contacts()
174 elif args.delete:
175 contact.delete_contact()
176 elif args.firstname:
177 contact.insert_contact()
178 elif args.update:
179 contact.update_contact()
180 elif args.listcontact:
181 contact.list_contact()
182 elif args.listsort:
183 contact.list_sort_by_last_name()
184
185
186
187contact = ContactBook()
188contact.main()