Тема: Чи буде таке рішення відповідати ООП, MVC та здоровому глузду?
Завдання створити записник із застосуванням ООП.
app.py
#!/python
"""
Application for storing and managing contacts
"""
from views import ContactView
def main():
while True:
print('Commands: 1 - List; 2 - Search; 3- Add; 4 - Delete; 0 - Exit')
command = input(' ?')
if command == '1':
ContactView.display_contact_list()
elif command == '2':
ContactView.search_contact()
elif command == '3':
ContactView.add_contact()
elif command == '4':
ContactView.del_contact()
elif command in {'0', 'q'}:
break
if __name__ == '__main__':
print(__doc__)
main()
settings.py
#!/python
import sqlite3
conn = sqlite3.connect('contact.db')
conn.execute("""create table if not exists CONTACT
(ID INT PRIMARY KEY NOT NULL,
FIRST_NAME TEXT NOT NULL,
LAST_NAME TEXT NOT NULL,
PHONE CHAR(15));""")
conn.commit()
models.py
#!/python
from settings import conn
class Contact:
""" Class Contact """
def __init__(self, first_name, last_name, phone):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
def __str__(self):
return "Name:{0} {1}\nPhone:{2}".format(self.first_name,
self.last_name,
self.phone)
@staticmethod
def get_contact_list():
cursor = conn.execute("""
select * from CONTACT;
""")
return cursor
@staticmethod
def delete_contact(pk):
conn.execute("""
DELETE FROM CONTACT WHERE ID=?;
""", (pk,))
conn.commit()
@staticmethod
def search_contact(ss): # ss is string_to_seacrh
cursor = conn.execute("""
SELECT * FROM CONTACT WHERE
FIRST_NAME LIKE ? OR LAST_NAME LIKE ? OR PHONE LIKE ?;
""", ('%{}%'.format(ss), '%{}%'.format(ss), '%{}%'.format(ss),))
return cursor
def is_contact(self):
cursor = conn.execute("""
SELECT * FROM CONTACT WHERE FIRST_NAME=? AND LAST_NAME=? LIMIT 1;
""", (self.first_name, self.last_name))
return len(cursor.fetchall()) == 1
def save_contact(self):
cursor = conn.execute("""
SELECT ID FROM CONTACT ORDER BY id DESC LIMIT 1;
""") # get last id from database
max_id_row = [row for row in cursor]
pk = max_id_row[0][0] + 1 if len(max_id_row) else 1
conn.execute("""
INSERT INTO CONTACT VALUES (?, ?, ?, ?);
""", (pk, self.first_name, self.last_name, self.phone))
conn.commit()
views.py
#!/python
from models import Contact
class ContactView:
""" Views for Contacts """
prefix = '\n\t=== > '
def _input_data(value_name, value_length=1):
""" Control for input data length """
while True:
print(ContactView.prefix, value_name,
' (min length - {})'.format(value_length))
value = input(' ?')
if len(value) >= value_length:
return value
def _contact_list_view(contact_list=[]):
""" Dispaly table """
print('-' * 111)
print(':{:5}: {:^40} : {:^40} : {:^15} :'.format(
'N', 'First Name', 'Last Name', 'Phone'))
print('-' * 111)
for k, contact in enumerate(contact_list):
print(':{:5}: {:^40} : {:^40} : {:^15} :'.format(
k + 1, *contact[1:]))
print('-' * 111)
def display_contact_list():
""" Dispaly all contacts """
cursor = Contact.get_contact_list()
contact_list = cursor.fetchall()
ContactView._contact_list_view(contact_list)
return contact_list
def add_contact():
""" Add contact if not exist """
first_name = ContactView._input_data('Enter First Name', 3)
last_name = ContactView._input_data('Enter Last Name', 3)
phone = ContactView._input_data('Enter Phone ', 3)
contact = Contact(first_name, last_name, phone)
if contact.is_contact():
print(ContactView.prefix,
'Can not add contact. This contact is present in database.')
return
contact.save_contact()
print(contact, ContactView.prefix, 'contact added')
def del_contact():
""" Delete contact is exist """
contact_list = ContactView.display_contact_list(
) # display contact list for delete choose to
if not contact_list:
print(ContactView.prefix,
'Database is empty.')
return
pk = input('Enter contact number to delete ?')
pk = int(pk) - 1 if pk.isdigit() else -1 # make 0-based
if 0 <= pk <= len(contact_list) - 1: # check is pk in range
Contact.delete_contact(contact_list[pk][0])
print(ContactView.prefix, 'Deleted')
return
print(ContactView.prefix, 'Number incorrect.')
def search_contact():
""" Search contact by name or phone and display """
ss = ContactView._input_data('Enter string to search', 2)
cursor = Contact.search_contact(ss)
ContactView._contact_list_view(cursor.fetchall())